-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbfs.java
More file actions
98 lines (77 loc) · 2.17 KB
/
bfs.java
File metadata and controls
98 lines (77 loc) · 2.17 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class graph {
int n,e;
HashMap<Integer,ArrayList<Integer>> list = new HashMap();
boolean v[];
int level[];
ArrayDeque<Integer> q = new ArrayDeque();
//Constructor takes input
graph(){
n = i(); //no of nodes
e = n-1; //no of egdes
for(int i=0;i<e;i++) //creating adjacency list
{
int a = i();
int b = i();
if(!list.containsKey(a))
list.put(a,new ArrayList());
if(!list.containsKey(b))
list.put(b,new ArrayList());
list.get(a).add(b);
list.get(b).add(a);
}
v = new boolean[n+1];
level = new int[n+1];
}
public void bfs(int root)
{
add(root); //Add to queue
v[root] = true; //mark visited
while(!q.isEmpty()) //while queue not empty
{
root = remove(); //remove first element from queue
ArrayList<Integer> ar = list.get(root);
for(int i : ar) //loop its neighbouring nodes
if(!v[i]) //If they are not visited
{
add(i); //add them to end of queue
v[i] = true; //and mark them visited
}
}
}
public static void main(String[] args)
{
graph g = new graph();
g.bfs(1);
}
void add(int a)
{
q.addFirst(a);
}
int remove()
{
return q.removeLast();
}
void p(int a)
{
System.out.print(a);
}
void p(String s)
{
System.out.print(s);
}
static Scanner sc = new Scanner(System.in);
static long l(){
return sc.nextLong();
}
static int i(){
return sc.nextInt();
}
static String s(){
return sc.nextLine();
}
}