-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.java
More file actions
43 lines (35 loc) · 1.14 KB
/
BFS.java
File metadata and controls
43 lines (35 loc) · 1.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
import java.util.LinkedList;
import java.util.Queue;
//-----------------BFS is done with Queue----------------
public class BFS {
private Queue<Integer> queue;
//-----constructor------
public BFS(){
queue = new LinkedList<Integer>();
}
public void bfs(int[][] adjacencyMatrix, int source)
{
int noOfVertex = adjacencyMatrix[source].length - 1;
int[] visited = new int[noOfVertex + 1]; // to hold the visited vertex
int i, element;
visited[source] = 1;
queue.add(source); // Add vertices to the queue
System.out.println("\nBFS Traversal of the graph");
// prints the visited vertex and removes from the queue
while (!queue.isEmpty())
{
element = queue.remove();
i = element;
System.out.print(i + " ");
while (i <= noOfVertex)
{
if (adjacencyMatrix[element][i] == 1 && visited[i] == 0)
{
queue.add(i);
visited[i] = 1;
}
i++;
}
}
}
}