所有可达路径
题目:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static ArrayList<Integer> path = new ArrayList<>();
static int n;
static int[][] graph;
static ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
int m=sc.nextInt();
graph = new int[n+1][n+1];
for(int i=0;i<m;i++){
int u=sc.nextInt();
int v=sc.nextInt();
graph[u][v]=1;
}
dfs(1);
if(res.isEmpty()){
System.out.println(-1);
}
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res.get(i).size(); j++) {
if(j==res.get(i).size()-1){
System.out.println(res.get(i).get(j));
}else{
System.out.print(res.get(i).get(j) + " ");
}
}
}
}
static void dfs(int d){
//入
path.add(d);
if(d==n){
//将路径添加到结果中
res.add(new ArrayList<>(path));
//返回上一个节点前,应该要把当前节点从路径中删除
path.remove(path.size()-1);
return;
}
for(int i=1;i<=n;i++){
if(graph[d][i]==1){
//下
dfs(i);
//回
}
}
//离
path.remove(path.size()-1);
}
}

在进入节点的时候,将该节点加入路径中,在离开节点的时候将该节点从路径中移除(路径集合中的最后一个值)
注意最后一个节点,当d=n时候,将路径添加到结果中后我们直接返回了,再返回前(离)要把最后一个节点从路径中删除。这样和前面的思路才能一致:在进入的时候添加节点,在离开的时候删除。

浙公网安备 33010602011771号