您的位置:首页 > 汽车 > 新车 > 代码随想录算法刷题训练营day50:卡码网(98):所有可达路径

代码随想录算法刷题训练营day50:卡码网(98):所有可达路径

2024/10/19 16:27:25 来源:https://blog.csdn.net/m0_46478505/article/details/141091959  浏览:    关键词:代码随想录算法刷题训练营day50:卡码网(98):所有可达路径

代码随想录算法刷题训练营day50:卡码网(98):所有可达路径

卡码网(98):所有可达路径
题目
在这里插入图片描述

代码

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;public class Main {static List<List<Integer>> result = new ArrayList<>(); // 收集符合条件的路径static List<Integer> path = new ArrayList<>(); // 1节点到终点的路径public static void dfs(int[][] graph, int x, int n) {// 当前遍历的节点x 到达节点nif (x == n) { // 找到符合条件的一条路径result.add(new ArrayList<>(path));return;}for (int i = 1; i <= n; i++) { // 遍历节点x链接的所有节点if (graph[x][i] == 1) { // 找到 x链接的节点path.add(i); // 遍历到的节点加入到路径中来dfs(graph, i, n); // 进入下一层递归path.remove(path.size() - 1); // 回溯,撤销本节点}}}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();int m = scanner.nextInt();// 节点编号从1到n,所以申请 n+1 这么大的数组int[][] graph = new int[n + 1][n + 1];for (int i = 0; i < m; i++) {int s = scanner.nextInt();int t = scanner.nextInt();// 使用邻接矩阵表示无向图,1 表示 s 与 t 是相连的graph[s][t] = 1;}path.add(1); // 无论什么路径已经是从1节点出发dfs(graph, 1, n); // 开始遍历// 输出结果if (result.isEmpty()) System.out.println(-1);for (List<Integer> pa : result) {for (int i = 0; i < pa.size() - 1; i++) {System.out.print(pa.get(i) + " ");}System.out.println(pa.get(pa.size() - 1));}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com