-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS
51 lines (44 loc) · 1.46 KB
/
BFS
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
import java.util.*;
public class Graph {
private int V;
private LinkedList <Integer>[] adjacency; // declaration of an array of LinkedList
public Graph(int nodes) {
V = nodes;
adjacency = new LinkedList[nodes]; // adjacency is the LinkedList of nodes
for (int i = 0; i < nodes; i++) {
adjacency[i] = new LinkedList<>();
}
}
// u -> v ( u = start vertex, v = final vertex)
public void addEdge(int u, int v) {
adjacency[u].add(v); // adding a pointer or another connection or another node to the two vertices
}
public void BFS(int startVertex) {
boolean visited[] = new boolean[V];
Queue<Integer> queue = new LinkedList<>();
visited[startVertex] = true;
queue.offer(startVertex) ;
while(!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
for(Integer neighbor : adjacency[vertex]){
if(!visited[neighbor]){
visited[neighbor] = true;
queue.offer(neighbor);
}
}
}
}
public static void main(String[] args) {
System.out.println("Hello World");
Graph g = new Graph(7); // number of nodes that are in the binary graph
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,3);
g.addEdge(1,4);
g.addEdge(2,5);
g.addEdge(2,6);
int startVertex = 0;
g.BFS(startVertex);
}
}