Problem Description
A robot is placed in an unknown room modeled as an m x n grid with walls and open spaces. You can control the robot with an API that lets it move forward, turn left/right, and clean the current cell. Initially facing up, the robot must clean all accessible cells, navigating based only on success or failure responses from its move actions. The challenge is to backtrack and explore the entire room without knowledge of the layout.
Key Insights
- Use DFS/backtracking to explore all directions from each cell.
- Represent cells with relative coordinates because the room layout is unknown.
- Maintain a visited set to avoid re-cleaning the same cell.
- After moving to a new cell, backtrack (rotate 180 degrees, move, then re-adjust orientation).
- Try all 4 directions with consistent relative adjustments (up, right, down, left).
Space and Time Complexity
Time Complexity: O(m * n) in the worst case where every cell is accessible. Space Complexity: O(m * n) due to the recursive stack and visited set.
Solution
We use a DFS/backtracking strategy to clean all reachable cells. Starting from the robot's initial location (assumed as coordinate (0, 0) in our relative system), we clean the current cell and mark it as visited. Then, for each of the 4 directions, we check if the robot can move into an unvisited cell. If the move is successful, we recursively clean from that new position. After exploring from the cell, we backtrack by turning 180 degrees, moving forward (to get back to the previous cell), and then turning 180 degrees again to reset the direction. This process is repeated for each cell until all accessible cells are cleaned. Key data structures include a set for tracking visited coordinates and an array representing the possible direction vectors.