所有可达路径

题目:

https://www.programmercarl.com/kamacoder/0098.%E6%89%80%E6%9C%89%E5%8F%AF%E8%BE%BE%E8%B7%AF%E5%BE%84.html#%E6%8F%92%E6%9B%B2

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时候,将路径添加到结果中后我们直接返回了,再返回前(离)要把最后一个节点从路径中删除。这样和前面的思路才能一致:在进入的时候添加节点,在离开的时候删除。

posted @ 2025-04-19 20:58  虾11  阅读(13)  评论(0)    收藏  举报