A girl and a robot thinking together

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

Follow the steps, then explain them in your own words
  1. EnterMark the room
  2. Call recursivelyExplore one neighbor
  3. ReturnGo back to the current room
  4. 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.