⬅ Previous Topic
Flatten a Binary Search Tree into a Sorted ListNext Topic ⮕
Depth-First Search in Graphs⬅ Previous Topic
Flatten a Binary Search Tree into a Sorted ListNext Topic ⮕
Depth-First Search in GraphsTopic Contents
Breadth-First Search (BFS) is a fundamental graph traversal algorithm that explores the neighbor nodes level by level. Given a starting node in a graph, BFS visits all its adjacent nodes, then moves on to their neighbors, and so on.
BFS is commonly used for finding the shortest path in unweighted graphs, level order traversal of trees, and in many other scenarios where step-wise discovery is important.
function bfs(graph, start) {
const visited = new Set();
const queue = [start];
const result = [];
visited.add(start);
while (queue.length > 0) {
const node = queue.shift();
result.push(node);
for (const neighbor of graph[node] || []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
return result;
}
const graph = {
0: [1, 2],
1: [0, 3],
2: [0],
3: [1]
};
console.log("BFS from node 0:", bfs(graph, 0)); // Output: [0, 1, 2, 3]
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | Even in the best case, BFS must explore every vertex (V) and every edge (E) to ensure complete traversal of the graph component. |
Average Case | O(V + E) | On average, BFS visits all vertices and edges once during the traversal. |
Worst Case | O(V + E) | In the worst case, such as a fully connected graph, BFS still processes all vertices and edges exactly once. |
O(V)
Explanation: The space complexity is proportional to the number of vertices because the queue and visited set each store up to V elements.
⬅ Previous Topic
Flatten a Binary Search Tree into a Sorted ListNext Topic ⮕
Depth-First Search in GraphsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.