Day50 >> 98、可达路径 + 广度优先搜索理论基础

代码随想录-图论Part1

深搜理论基础

98、可达路径

java 复制代码
import java.util.*;


public class Main {
    static List<List<Integer>> result = new ArrayList<>();
    static List<Integer> path = new ArrayList<>();

    public static void dfs(int[][] graph, int x, int n) {
        if (x == n) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 1; i <= n; i++) {
            if (graph[x][i] == 1) {
                path.add(i);
                dfs(graph, i, n);
                path.remove(path.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();

        int[][] graph = new int[n + 1][n + 1];

        for (int i = 0; i < m; i++) {
            int s = sc.nextInt();
            int t = sc.nextInt();
            graph[s][t] = 1;
        }

        path.add(1);
        dfs(graph, 1, n);

        if (result.isEmpty()) System.out.println(-1);

        for (List<Integer> p : result) {
            for (int i = 0; i < p.size() - 1; i++) {
                System.out.print(p.get(i) + " ");
            }
            System.out.println(p.get(p.size() - 1));
        }
    }
}

广度优先搜索理论基础

相关推荐
AI-Ming26 分钟前
注意力机制
算法·ai·ai编程
ℳ๓₯㎕.空城旧梦40 分钟前
C++中的解释器模式
开发语言·c++·算法
x_xbx1 小时前
LeetCode:2. 两数相加
算法·leetcode·职场和发展
兔子7731 小时前
RNN 终于讲明白了:从“模型为什么需要记忆”到 Elman 1990 全文吃透
算法
兔子7731 小时前
LSTM 终于讲明白了:从“RNN 为什么会忘”到 Hochreiter & Schmidhuber 1997 全文吃透
算法
ECT-OS-JiuHuaShan1 小时前
朱梁万有递归元定理,重构《阴符经》
算法·重构
_日拱一卒1 小时前
LeetCode:最长连续序列
算法·leetcode·职场和发展
2401_879503411 小时前
C++与FPGA协同设计
开发语言·c++·算法
重生之后端学习1 小时前
287. 寻找重复数
数据结构·算法·leetcode·深度优先·图论
抓个马尾女孩2 小时前
位置编码:绝对位置编码、相对位置编码、旋转位置编码
人工智能·深度学习·算法·transformer