-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.java
More file actions
31 lines (25 loc) · 1.1 KB
/
bfs.java
File metadata and controls
31 lines (25 loc) · 1.1 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
import java.util.*;
public class bfs {
public static void bfs(Map<Integer, List<Integer>> graph, int startNode, int numberOfNodes) {
// Initialize a queue for BFS
Queue<Integer> queue = new LinkedList<>();
// Array to keep track of visited nodes
boolean[] visited = new boolean[numberOfNodes];
// Start BFS from the startNode
queue.add(startNode);
visited[startNode] = true;
while (!queue.isEmpty()) {
// Dequeue a node from the front
int currentNode = queue.poll();
System.out.print(currentNode + " "); // Print the current node
// Iterate through all neighbors of the current node
for (int neighbor : graph.getOrDefault(currentNode, new ArrayList<>())) {
// If the neighbor is not visited, mark it as visited and enqueue it
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
}