Robot Room Cleaner Problem
Description
LeetCode Problem 489.
You are controlling a robot that is located somewhere in a room. The room is modeled as an m x n binary grid where 0 represents a wall and 1 represents an empty slot.
The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API Robot.
You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is 90 degrees.
When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.
Design an algorithm to clean the entire room using the following APIs:
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
Note that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.
Custom testing:
The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.
Example 1:

Input: room = [[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,1,1,1,1,1],[0,0,0,1,0,0,0,0],[1,1,1,1,1,1,1,1]], row = 1, col = 3
Output: Robot cleaned all rooms.
Explanation: All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
Example 2:
Input: room = [[1]], row = 0, col = 0
Output: Robot cleaned all rooms.
Constraints:
m == room.lengthn == room[i].length1 <= m <= 1001 <= n <= 200room[i][j]is either0or1.0 <= row < m0 <= col < nroom[row][col] == 1- All the empty cells can be visited from the starting position.
Solution
Approach: DFS with Backtracking
We cannot see the grid, but we do not need to: we can draw our own map as we go. Call the starting cell (0, 0) and the starting direction "up". Every time the robot moves, we update its position ourselves, so coordinates relative to the start are enough to remember which cells we have already cleaned.
Now explore like a depth-first search. At a cell (i, j) where the robot faces direction d:
- Mark the cell as visited and clean it.
- Try the four directions in clockwise order, starting with the one it faces. Since up, right, down, left are each one
turnRight()apart, after trying a direction we just turn right to face the next one. - If the neighbor in that direction is not visited and
move()succeeds, recurse into it with that direction.
The tricky part is backtracking. In a normal DFS, returning from a call puts us back at the parent for free. Here the robot has physically moved, so after the recursive call we must drive it back: turn around (two right turns), move one step, and turn around again so it faces the same direction as before the call. Only then does the next turnRight() point it in the right direction. Without this, the robot's real position and our recorded position drift apart.
Each recursive call tries four directions and then turns right four times in total, so when it returns the robot faces the direction it came in with, which is exactly what the backtracking step expects.
A wall and a visited cell are treated the same way: we skip them. Checking visited before calling move() matters, because a successful move into an already cleaned cell would have to be undone.
Complexity: O(N) time, where N is the number of empty cells: each cell is entered once and does a constant number of moves and turns. O(N) space for the visited set and the recursion stack.
class Solution:
def cleanRoom(self, robot):
"""
:type robot: Robot
:rtype: None
"""
dirs = ((-1, 0), (0, 1), (1, 0), (0, -1)) # up, right, down, left: one turnRight apart
visited = set()
# The robot is at (i, j) relative to the start, facing direction d.
def dfs(i, j, d):
visited.add((i, j))
robot.clean()
for k in range(4):
nd = (d + k) % 4
x, y = i + dirs[nd][0], j + dirs[nd][1]
if (x, y) not in visited and robot.move():
dfs(x, y, nd)
# go back to (i, j) and face nd again
robot.turnRight()
robot.turnRight()
robot.move()
robot.turnRight()
robot.turnRight()
robot.turnRight() # next direction
dfs(0, 0, 0)