@icr0/

bfs-implementation

Java

No description

fork
loading
Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.*;
class Main {
  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    ArrayList<Integer>[] g = new ArrayList[n];
    for(int i = 0;i<n;i++){
      g[i] = new ArrayList<Integer>();
    }
    for(int i = 0;i<n-1;i++){
      g[in.nextInt()].add(in.nextInt());
    }
    int[] dist = new int[n];
    Arrays.fill(dist,99999);
    ArrayDeque<Integer> q = new ArrayDeque();
    q.add(0);
    dist[0] = 0;
    while(!q.isEmpty()){
      int cur = q.poll();
      System.out.println("CURNODE: "+cur);
      for(int i =0;i<g[cur].size();i++){
        int next = g[cur].get(i);
        dist[next] = Math.min(dist[cur]+1,dist[next]);
        q.add(next);
      }
    }
    System.out.println(Arrays.toString(dist));
  }
}