BFS
BFS
Breadth-First Search (BFS) is a graph traversal algorithm that explores nodes level-by-level, visiting all neighbor nodes at the current depth before moving deeper. It employs a FIFO Queue to orchestrate vertex traversal. BFS is guaranteed to discover the shortest path in unweighted graphs.
Complexity Profile
| Case | Complexity |
|---|---|
| Best Case | O(V + E) |
| Average Case | O(V + E) |
| Worst Case | O(V + E) |
| Space Complexity | O(V) |
Code Implementation
from collections import deque
def breadth_first_search(graph, start_node):
visited = set()
queue = deque([start_node])
visited.add(start_node)
while queue:
current = queue.popleft() # Dequeue
print("Visited node:", current)
for neighbor in graph.get(current, []):
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor) # EnqueueReal-World Applications
- Finding shortest path in unweighted networks.
- Social network analysis (finding friends within degrees of connection).
- Web crawlers indexing local links level by level.
Dijkstra
Dijkstra's algorithm finds the shortest paths from a single source node to all other nodes in a weighted graph with non-negative edge weights. It acts as a greedy algorithm, maintaining a priority queue of candidate vertices and relaxing paths continuously.
Binary Search
Binary search is an efficient search algorithm that works on pre-sorted arrays. It repeatedly splits the search interval in half. If the target value is less than the middle element, it narrows the interval to the lower half; otherwise, it limits it to the upper half, repeating the split until the value is found or the interval is empty.