
Think together · Start with a little story
Whenever the robot enters a room, it says, “Check the neighbors of this room in the same way.” That sounds like a function calling itself.
Lay out the process
- EnterMark the room
- Call recursivelyExplore one neighbor
- ReturnGo back to the current room
- ContinueTry the next unvisited neighbor
Recursion naturally expresses the downward exploration and return steps of DFS.
Each call remembers the current room and which direction to try next. You can also implement DFS with an explicit stack; recursion is not required.
Your turn to try
Can you write DFS by managing your own stack without recursion?
Ready? Open to see the explanation
Yes. The key is to preserve depth-first visit order and the state needed to return.