图论理论基础
大家可以在看图论理论基础的时候,很多内容 看不懂,例如也不知道 看完之后 还是不知道 邻接矩阵,邻接表怎么用, 别着急。
理论基础大家先对各个概念有个印象就好,后面在刷题的过程中,每个知识点都会得到巩固。
深搜理论基础
了解一下深搜的原理和过程
98. 所有可达路径
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static List<List<Integer>> paths = new ArrayList<>();
static List<Integer> currentPath = new ArrayList<>();
public static void dfs(int[][] graph, int currentNode, int endNode) {
if (currentNode == endNode) {
paths.add(new ArrayList<>(currentPath));
return;
}
for (int nextNode = 1; nextNode <= endNode; nextNode++) {
if (graph[currentNode][nextNode] == 1) {
currentPath.add(nextNode);
dfs(graph, nextNode, endNode);
currentPath.remove(currentPath.size() - 1);
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] graph = new int[n + 1][n + 1];
for (int i = 0; i < m; i++) {
int startNode = scanner.nextInt();
int endNode = scanner.nextInt();
graph[startNode][endNode] = 1;
graph[endNode][startNode] = 1;
}
currentPath.add(1);
dfs(graph, 1, n);
if (paths.isEmpty()) System.out.println(-1);
for (List<Integer> path : paths) {
for (int i = 0; i < path.size() - 1; i++) {
System.out.print(path.get(i) + " ");
}
System.out.println(path.get(path.size() - 1));
}
scanner.close();
}
}