BFS explores neighbors layer by layer with a queue—shortest path in unweighted graphs. DFS goes deep first with stack/recursion—cycle detection, topological sort, connected components.
BFS skeleton
- Enqueue start, mark visited
- Dequeue u, process, enqueue unvisited neighbors
- Track distance[] for shortest path layers
DFS skeleton
- Mark visited, process node
- Recurse on unvisited neighbors
- Backtrack implicitly when returning
Backtracking preview
Backtracking is DFS with undo: choose, recurse, unchoose—used for subsets, permutations, and constraint puzzles (N-queens). Prune branches that violate constraints early.
BFS on small graph
#include
#include
#include
int main() {
std::vector> adj = {{1, 2}, {0, 3}, {0}, {1}};
std::vector vis(4);
std::queue q;
q.push(0); vis[0] = true;
std::cout << "BFS: ";
while (!q.empty()) {
int u = q.front(); q.pop();
std::cout << u << " ";
for (int v : adj[u])
if (!vis[v]) { vis[v] = true; q.push(v); }
}
std::cout << "\n";
return 0;
}
Important interview questions and answers
- Q: BFS vs DFS shortest path?
A: BFS on unweighted graph finds shortest path; DFS does not guarantee shortest. - Q: Visited array why?
A: Prevents infinite loops on cycles.
Self-check
- What data structure does BFS use?
- Time complexity BFS on V vertices E edges?
Tip: Always mark visited when enqueue/push—cycles cause infinite loops otherwise.
Interview prep
- BFS shortest path?
Unweighted graphs—first visit is shortest layer distance.
- Visited array?
Prevents cycles and redundant work.
- DFS use?
Cycle detection, topo sort, components, backtracking base.