-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadthFirstSearch.java
More file actions
78 lines (65 loc) · 1.36 KB
/
Copy pathBreadthFirstSearch.java
File metadata and controls
78 lines (65 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.Stack;
public class BreadthFirstSearch {
public static void main(String[] args){
//Preparing Graph
NodeBFS n1= new NodeBFS();
n1.data=1;
NodeBFS n2= new NodeBFS();
n2.data=2;
NodeBFS n3= new NodeBFS();
n3.data=3;
NodeBFS n4= new NodeBFS();
n4.data=4;
NodeBFS n5= new NodeBFS();
n5.data=5;
n1.first=n2;
n1.second=n3;
n3.first=n1;
n3.second=n2;
n3.third=n4;
n2.first=n1;
n2.second=n5;
n2.third=n3;
n2.fourth=n4;
n4.first=n5;
n4.second=n2;
n4.third=n3;
n5.first=n2;
n5.second=n4;
doBFS(n1);
}
static void doBFS(NodeBFS root){
Queue<NodeBFS> q=new Queue<NodeBFS>();
root.visited=true;
q.enqueue(root);
NodeBFS current;
while(!q.isEmpty()){
current=q.dequeue();
System.out.println(current.data);
if(current.first!=null && current.first.visited==false){
current.first.visited=true;
q.enqueue(current.first);
}
if(current.second!=null && current.second.visited==false){
current.second.visited=true;
q.enqueue(current.second);
}
if(current.third!=null && current.third.visited==false){
current.third.visited=true;
q.enqueue(current.third);
}
if(current.fourth!=null && current.fourth.visited==false){
current.fourth.visited=true;
q.enqueue(current.fourth);
}
}
}
}
class NodeBFS{
int data;
NodeBFS first;
NodeBFS second;
NodeBFS third;
NodeBFS fourth;
boolean visited;
}