-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadth_First_Search.java
More file actions
53 lines (44 loc) · 1.35 KB
/
Breadth_First_Search.java
File metadata and controls
53 lines (44 loc) · 1.35 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
package com.dsj.graphs;
import java.util.LinkedList;
import java.util.Queue;
public class Breadth_First_Search {
Queue<Integer> queue;
Graph_Creation_Adj_List graph_to_be_searched;
boolean visitedVertexArr[];
int numberOfVertices;
public Breadth_First_Search(Graph_Creation_Adj_List graph_to_be_searched) {
this.graph_to_be_searched = graph_to_be_searched;
queue = new LinkedList<Integer>();
bfs();
}
private void bfs() {
System.out.println("BFS begins.");
numberOfVertices = graph_to_be_searched.numberOfVertices;
visitedVertexArr = new boolean[numberOfVertices];
updateVertexStatus(0);
traverse(queue.peek());
System.out.println("BFS Completed.");
}
private void traverse(int index) {
int temp = queue.remove();
updateVertexStatus(temp);
if (!queue.isEmpty()) {
traverse(queue.peek());
}
}
private void updateVertexStatus(int index) {
System.out.println(graph_to_be_searched.arrIndexToVertexMap.get(index));
visitedVertexArr[index] = true;
insertAdjVertices(index);
}
private void insertAdjVertices(int index) {
graph_to_be_searched.adjList[index].forEach(connectedNodes -> {
int temp = graph_to_be_searched.getIndexForThis(connectedNodes.getVertexId());
if (!visitedVertexArr[temp]) {
if (!queue.contains(temp)) {
queue.add(temp);
}
}
});
}
}