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