DSA, Database System & Operating System β Sorting, Searching, and Graphs, NEC licence examination syllabus (Nepal Engineering Council).
Two fundamentally different strategies for visiting every reachable vertex β one goes deep, one goes wide.
DFS (Depth First)Go as deep as possible down one path before backtracking β uses a STACK (or recursion) internally.
BFS (Breadth First)Visit all neighbours at the current distance before going further β uses a QUEUE internally, and naturally finds the SHORTEST path in an unweighted graph.
The stack-versus-queue distinction is the mechanism. The exam question is usually which one to pick, and that follows from what each guarantees.
Shortest path, unweightedBFS β it reaches every vertex by the fewest edges, because it exhausts distance 1 before touching distance 2.
Does a path exist?Either. Both visit exactly the reachable set.
Cycle detection, topological sortDFS β its recursion stack is what reveals a back edge to a vertex still being explored.
Deep or infinite graphsBFS β DFS can descend forever down one branch and never return.
Memory is tightDFS β it stores one path, O(depth). BFS stores an entire level, which on a wide graph can be enormous.
Each vertex is marked visited once, and each edge is examined once from each end. So the total is proportional to vertices plus edges rather than to either alone β assuming an adjacency list, since a matrix forces an O(V) scan per vertex and pushes both to O(VΒ²).
Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Loadingβ¦