-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.java
More file actions
61 lines (46 loc) · 1.36 KB
/
BFS.java
File metadata and controls
61 lines (46 loc) · 1.36 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.mycompany.algorithm_final_project;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
*
* @author israkkayumchowdhury
*/
public class BFS {
private final int N = (int) (1e5 + 10);
ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>(N);
int[] vis = new int[N];
Scanner s = new Scanner(System.in);
public void bfs(int source){
Queue<Integer> q = new LinkedList<>();
q.add(source);
vis[source] = 1;
while(!q.isEmpty()){
int cur_v = q.peek();
q.poll();
System.out.print(cur_v +" ");
Iterator<Integer> i = g.get(cur_v).listIterator();
while(i.hasNext()){
int child = i.next();
if(vis[child] != 1){
q.add(child);
vis[child] = 1;
}
}
}
}
public void bfs_graph() {
int n = s.nextInt();
for(int i = 0; i < N; ++i)
g.add(new ArrayList<Integer>());
for(int i = 0; i < n-1; ++i){
int x = s.nextInt();
int y = s.nextInt();
g.get(x).add(y);
g.get(y).add(x);
}
bfs(1);
}
}