How do you decide between BFS and DFS - and how do you recognise a graph problem that nobody described as a graph?
Choose BFS when the question asks for the fewest steps in an unweighted graph or when you need results in distance order; choose DFS when you are asking a structural question such as connectivity, cycles or topological order, or when the graph is deep and narrow.
Answer
Short answer
Use BFS for the fewest steps in an unweighted graph or when results must come back in distance order. Use DFS for structural questions such as connectivity, cycles or topological order, or when the graph is deep and narrow.
Keep graphs explicit in the answer because that is the concept the interviewer is actually trying to test. A good graphs explanation names the trade-off, the failure mode, and the evidence you would use before choosing. Use graphs once more at the decision point so the answer reads as judgement rather than a detached example.
Keep graphs explicit in the answer because that is the concept the interviewer is actually trying to test. A good graphs explanation names the trade-off, the failure mode, and the evidence you would use before choosing.
Was this answer helpful?
Likely follow-ups
- The edges now have weights of 0 or 1. What is the cheapest change to your BFS?
- How would you detect a cycle in a directed graph, and why is the undirected version different?
- Your DFS overflows the stack on a graph with a million nodes. What do you do?
- Give me a problem you have seen that was a graph problem in disguise, and name its nodes and edges.
Related questions
- Find the cheapest flight from one city to another using at most K stops. Why does plain Dijkstra give the wrong answer?mediumAlso on graphs5 min
- Find the cheapest route between two nodes in a weighted directed graph. Then tell me what breaks if one edge has a negative weight.mediumAlso on graphs5 min
- You are given a set of tasks and their prerequisites. Produce a valid execution order, or report that none exists.mediumAlso on graphs6 min
- Count the islands in a grid of land and water. Then land is added one cell at a time, and you report the island count after every addition.mediumAlso on graphs5 min