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

广度优先搜索理论基础

相关推荐
那个村的李富贵19 小时前
CANN加速下的AIGC“即时翻译”:AI语音克隆与实时变声实战
人工智能·算法·aigc·cann
power 雀儿19 小时前
Scaled Dot-Product Attention 分数计算 C++
算法
琹箐19 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
renhongxia120 小时前
如何基于知识图谱进行故障原因、事故原因推理,需要用到哪些算法
人工智能·深度学习·算法·机器学习·自然语言处理·transformer·知识图谱
坚持就完事了20 小时前
数据结构之树(Java实现)
java·算法
算法备案代理20 小时前
大模型备案与算法备案,企业该如何选择?
人工智能·算法·大模型·算法备案
赛姐在努力.20 小时前
【拓扑排序】-- 算法原理讲解,及实现拓扑排序,附赠热门例题
java·算法·图论
野犬寒鸦21 小时前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法
霖霖总总21 小时前
[小技巧66]当自增主键耗尽:MySQL 主键溢出问题深度解析与雪花算法替代方案
mysql·算法
rainbow688921 小时前
深入解析C++STL:map与set底层奥秘
java·数据结构·算法