-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFSAlgorithm
More file actions
101 lines (79 loc) · 2.14 KB
/
BFSAlgorithm
File metadata and controls
101 lines (79 loc) · 2.14 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
99
100
101
//Main Class
package bfsalgorithm;
/**
*
* @author Shaon Bhatta Shuvo
*/
public class BFSAlgorithm {
public static void main(String[] args) {
BFS bfs = new BFS();
Vertex A = new Vertex('A');
Vertex B = new Vertex('B');
Vertex C = new Vertex('C');
Vertex D = new Vertex('D');
Vertex E = new Vertex('E');
A.addNeighbourVertex(B);
A.addNeighbourVertex(D);
D.addNeighbourVertex(E);
B.addNeighbourVertex(C);
bfs.BFS_Implementation(A);
}
//Vertex Class
package bfsalgorithm;
import java.util.ArrayList;
import java.util.List;
public class Vertex {
private char data;
private boolean visited;
private List<Vertex> neighbourList;
public Vertex(char data){
this.data =data;
this.neighbourList = new ArrayList<>();
}
public char getData() {
return data;
}
public void setData(char data) {
this.data = data;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public List<Vertex> getNeighbourList() {
return neighbourList;
}
public void setNeighbourList(List<Vertex> neighbourList) {
this.neighbourList = neighbourList;
}
public void addNeighbourVertex(Vertex vertex){
neighbourList.add(vertex);
}
@Override
public String toString(){
return " "+this.data;
}
}
//BFS implementation class
package bfsalgorithm;
import java.util.LinkedList;
import java.util.Queue;
public class BFS {
public void BFS_Implementation(Vertex root){
Queue<Vertex> queue = new LinkedList<>();
root.setVisited(true);
queue.add(root);
while(!queue.isEmpty()){
Vertex actualVertex = queue.remove();
System.out.println(actualVertex+" ");
for (Vertex v : actualVertex.getNeighbourList()){
if(!v.isVisited()){
v.setVisited(true);
queue.add(v);
}
}
}
}
}