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));
        }
    }
}

广度优先搜索理论基础

相关推荐
IronMurphy5 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬5 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership5 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826525 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u6 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
_深海凉_9 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
旖-旎10 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰10 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx10 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
AIFarmer11 小时前
【无标题】
开发语言·c++·算法