DFS错了求助
查看原帖
DFS错了求助
345765
fldfld楼主2022/7/30 16:48
import java.util.*;
import java.io.*;
public class Main{

    static BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
    static StreamTokenizer st =new StreamTokenizer(in);
    public static int nextInt() throws IOException {
        st.nextToken();
        return (int)st.nval;
    }
    static boolean [] isvisted;
    public static void main(String[] args)throws IOException {
        int n = nextInt();
        int m = nextInt();
        List<Integer>[] graph = new List[100001];

        isvisted = new boolean[100001];
        
        for(int i = 0;i<graph.length;i++){
            graph[i] = new ArrayList<>();
        }
        for(int i = 0;i<m;i++){
            int u = nextInt();
            int v = nextInt();
            graph[u].add(v);
        }
        //.........------------------------
    dfs(1,graph );
        // Arrays.fill(isvisted,false);
        // System.out.println();
         bfs(1,graph);

    }
public static void dfs(int i,List<Integer>[]graph){
        isvisted[i] = true;
        System.out.print(i+" ");
       for(Integer adj : graph[i]){
          if(isvisted[adj] != true) {
              dfs(adj, graph);
          }
      }
}
public static  void bfs(int i,List<Integer>[] graph){
     Queue<Integer> queue = new LinkedList<>();
     queue.add(i);
    isvisted[i] = true;
     while(queue.isEmpty() != true){
           int q = queue.poll();
     
           System.out.print(q+" ");
           for(Integer adj: graph[q]){
               if(isvisted[adj]!=true){
                   isvisted[adj] = true;
                   queue.offer(adj);
               }
               
           }
     }
}
}

PS dfs里加一个排序 也只能过一个测试点

2022/7/30 16:48
加载中...