Solving "Robot Room Cleaner" Problem
Techniques to solve "Robot Room Cleaner" problems on Leetcode and in interviews.
Problem Statement
Given a robot cleaner in a room modeled as a grid.
Each cell in the grid can be empty or blocked.
The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees.
When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell.
Design an algorithm to clean the entire room using only the 4 given APIs shown below.
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();
}
Example:
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
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.
Notes:
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 mentioned 4 APIs, without knowing the room layout and the initial robot's position.
The robot's initial position will always be in an accessible cell.
The initial direction of the robot will be facing up.
All accessible cells are connected, which means the all cells marked as 1 will be accessible by the robot.
Assume all four edges of the grid are all surrounded by wall.
Solution
The idea is simple. Similar to how we do traversal in a grid using Depth First Search (DFS), we do DFS traversal on the input grid. Only thing that is different in this problem is that we have to additionally use the robot interface to control the robot’s direction and coordinates.
Inside each new cell which is not an obstacle call robot.clean()
In order to traverse all the 4 directions, call the api robot.turnRight() each time.
Whenever the robot has cleaned up all possible cells reachable from (row, col), backtrack to the previous cell and point in the same direction and then repeat.
Here is a python version of the solution using DFS:
def get_next_coord_from_dir(r, c, dir):
# get the new coordinates from (r, c) along direction dir
# dir = 0, points upwards
# dir = 1, points to the right
# dir = 2, points downwards
# dir = 3, points to the left
new_r, new_c = r, c
if dir == 0:
r -= 1
elif dir == 1:
c += 1
elif dir == 2:
r += 1
else:
c -= 1
return r, c
def turn_back():
robot.turnRight()
robot.turnRight()
robot.move()
robot.turnRight()
robot.turnRight()
def dfs(room, srow, scol, curr_dir, visited):
robot.clean()
visited.add((srow, scol))
for j in range(4):
robot.turnRight()
curr_dir = (curr_dir + 1) % 4
r, c = get_next_coord_from_dir(srow, scol, curr_dir)
if (r, c) not in visited:
# cell ok to visit
ok = robot.move()
if ok:
dfs(room, r, c, curr_dir, visited)
# backtrack to the previous cell. Recursion automatically
# takes care of this but we need to explicitly instruct
# the robot.
turn_back()
if __name__ == '__main__':
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]
]
for i in range(len(room)):
for j in range(len(room[0])):
if room[i][j] == 1:
visited = set()
dfs(room, i, j, 0, visited)
for i1 in range(len(room)):
for j1 in range(len(room[0])):
if room[i1][j1] == 1:
assert (i1, j1) in visited, f"Not cleaned {i1}, {j1}"
Non-recursive version of the above DFS search (using stack):
def clean_room(room, srow, scol, dir, visited):
cnt = 0
robot.clean()
visited.add((srow, scol))
stack = [[srow, scol, dir]]
while True:
if len(stack) == 0:
break
# get the current cell state
srow, scol, dir = stack[-1]
if cnt == 4:
# all neighbors has been cleaned or not reachable
stack.pop()
if len(stack) == 0:
break
# backtrack to the previous cell and point in the same direction
turn_back()
cnt = 0
else:
# explore all neighbors
robot.turnRight()
dir = (dir + 1) % 4
stack[-1][2] = dir
cnt += 1
r, c = get_next_coord_from_dir(srow, scol, dir)
if (r, c) not in visited:
ok = robot.move()
if ok:
srow, scol = r, c
stack.append([srow, scol, dir])
visited.add((srow, scol))
robot.clean()
cnt = 0
if __name__ == '__main__':
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]
]
for i in range(len(room)):
for j in range(len(room[0])):
if room[i][j] == 1:
visited = set()
clean_room(room, i, j, 0, visited)
for i1 in range(len(room)):
for j1 in range(len(room[0])):
if room[i1][j1] == 1:
assert (i1, j1) in visited, f"Not cleaned {i1}, {j1}"
Time complexity is O(N*M) where N is number of rows in grid and M is number of columns. Additional space complexity is O(N*M) to maintain the visited array and stack.