Skip to content

Commit 8d4daa4

Browse files
committed
add graphbfs in java
1 parent 7bb1272 commit 8d4daa4

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Graphs/GraphBFS.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* The GraphBFS class represents a simple undirected graph using an adjacency list
3+
* and provides a breadth-first search (BFS) algorithm to traverse the graph.
4+
*/
5+
import java.util.*;
6+
import java.io.*;
7+
8+
class GraphBFS {
9+
private int V; // Number of vertices in the graph
10+
private List<Integer> adjacency[]; // Adjacency list to represent the graph
11+
12+
// Constructor to initialize the graph with the given number of vertices
13+
GraphBFS(int v) {
14+
V = v;
15+
adjacency = new ArrayList[V];
16+
for(int i = 0; i < V; i++) {
17+
adjacency[i] = new ArrayList<Integer>();
18+
}
19+
}
20+
21+
// Method to add an edge between vertices 'u' and 'v' in the graph
22+
void addEdge(int u, int v) {
23+
adjacency[u].add(v);
24+
adjacency[v].add(u);
25+
}
26+
27+
/**
28+
* Performs breadth-first search (BFS) starting from the given source vertex 's'.
29+
* Prints the vertices in BFS order.
30+
* @param s The source vertex from which BFS starts.
31+
*/
32+
void bfs(int s) {
33+
boolean[] visited = new boolean[V]; // Array to track visited vertices
34+
visited[s] = true; // Mark the source vertex as visited
35+
LinkedList<Integer> Q = new LinkedList<Integer>(); // Queue for BFS traversal
36+
Q.add(s); // Enqueue the source vertex
37+
38+
// BFS traversal
39+
while(Q.size() != 0) {
40+
int current = Q.poll(); // Dequeue the current vertex
41+
System.out.print(current + " -> "); // Print the current vertex
42+
43+
// Visit all neighbors of the current vertex
44+
for(int neighbour: adjacency[current]) {
45+
if(!visited[neighbour]) {
46+
visited[neighbour] = true; // Mark the neighbour as visited
47+
Q.add(neighbour); // Enqueue the neighbour for further exploration
48+
}
49+
}
50+
}
51+
}
52+
53+
// Main method for testing the GraphBFS class
54+
public static void main(String[] args) {
55+
GraphBFS g = new GraphBFS(5); // Create a graph with 5 vertices
56+
g.addEdge(2, 3); // Add edges to the graph
57+
g.addEdge(2, 4);
58+
g.addEdge(3, 1);
59+
g.addEdge(4, 1);
60+
61+
g.bfs(2); // Perform BFS starting from vertex 2
62+
}
63+
}

0 commit comments

Comments
 (0)