Courses / Computer Science I
Algorithmics

Graph Algorithms and Traversal

Computer Science I 184 words Free to read

Network Traversal: BFS vs DFS

Once data is a graph, traversal (systematically visiting vertices along edges) is the fundamental operation. Two strategies dominate, differing only in the data structure and order of exploration.

StrategyData StructureExploration PatternKey Use Case
BFSQueue (FIFO)Ripples outward, level by levelShortest path on unweighted graphs
DFSStack (LIFO)Plunges deep, then backtracksTopological sorting & cycle detection

Both strategies visit each vertex and edge a constant number of times, running in O(V+E)O(V + E) time.

Weighted Graphs & Pitfalls

For weighted graphs where edges carry costs, standard BFS fails. Dijkstra's algorithm greedily expands the nearest unsettled vertex using a priority queue (heap), finding shortest paths when weights are non-negative.

Complexity=O(V+E)\text{Complexity} = O(V + E)

Common pitfall: Forgetting the visited set. In a cyclic graph, omitting this causes infinite loops or exponential re-exploration.

Every graph traversal must track visited vertices to guarantee termination and process each vertex exactly once.

Graph Algorithms and Traversal

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes

Algorithmics