Robot Room Cleaner — LeetCode 489 Python Solution
- Problem
- #489
- Pattern
- Backtracking
- Reading time
- 10 min
- Source
- leetcode.com
The problem
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.
Example
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();
}Python solution
# """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
# class Robot:
# def move(self):
# """
# Returns true if the cell in front is open and robot moves into the cell.
# Returns false if the cell in front is blocked and robot stays in the current cell.
# :rtype bool
# """
#
# def turnLeft(self):
# """
# Robot will stay in the same cell after calling turnLeft/turnRight.
# Each turn will be 90 degrees.
# :rtype void
# """
#
# def turnRight(self):
# """
# Robot will stay in the same cell after calling turnLeft/turnRight.
# Each turn will be 90 degrees.
# :rtype void
# """
#
# def clean(self):
# """
# Clean the current cell.
# :rtype void
# """
class Solution:
def cleanRoom(self, robot):
"""
:type robot: Robot
:rtype: None
"""
def dfs(i, j, d):
vis.add((i, j))
robot.clean()
for k in range(4):
nd = (d + k) % 4
x, y = i + dirs[nd], j + dirs[nd + 1]
if (x, y) not in vis and robot.move():
dfs(x, y, nd)
robot.turnRight()
robot.turnRight()
robot.move()
robot.turnRight()
robot.turnRight()
robot.turnRight()
dirs = (-1, 0, 1, 0, -1)
vis = set()
dfs(0, 0, 0)Complexity
| Measure | Complexity |
|---|---|
| Time | Exponential (worst case) |
| Space | O(depth) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 489. Robot Room Cleaner is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 489. Robot Room Cleaner?
- LeetCode 489. Robot Room Cleaner is rated Hard on LeetCode.
- What topics does LeetCode 489. Robot Room Cleaner cover?
- LeetCode 489. Robot Room Cleaner is tagged Backtracking and Interactive on LeetCode.
- Is LeetCode 489. Robot Room Cleaner a premium problem?
- Yes. LeetCode 489. Robot Room Cleaner is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.