Number of Spaces Cleaning Robot Cleaned — LeetCode 2061 Python Solution
- Problem
- #2061
- Pattern
- Matrix and Grid
- Reading time
- 4 min
- Source
- leetcode.com
The problem
A room is represented by a 0-indexed 2D binary matrix room where a 0 represents an empty space and a 1 represents a space with an object. The top left corner of the room will be empty in all test cases.
Python solution
class Solution:
def numberOfCleanRooms(self, room: List[List[int]]) -> int:
def dfs(i, j, k):
if (i, j, k) in vis:
return
nonlocal ans
ans += room[i][j] == 0
room[i][j] = -1
vis.add((i, j, k))
x, y = i + dirs[k], j + dirs[k + 1]
if 0 <= x < len(room) and 0 <= y < len(room[0]) and room[x][y] != 1:
dfs(x, y, k)
else:
dfs(i, j, (k + 1) % 4)
vis = set()
dirs = (0, 1, 0, -1, 0)
ans = 0
dfs(0, 0, 0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m·n) |
| Space | O(1) to O(m·n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2061. Number of Spaces Cleaning Robot Cleaned is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2061. Number of Spaces Cleaning Robot Cleaned?
- LeetCode 2061. Number of Spaces Cleaning Robot Cleaned is rated Medium on LeetCode.
- What topics does LeetCode 2061. Number of Spaces Cleaning Robot Cleaned cover?
- LeetCode 2061. Number of Spaces Cleaning Robot Cleaned is tagged Array, Matrix and Simulation on LeetCode.
- Is LeetCode 2061. Number of Spaces Cleaning Robot Cleaned a premium problem?
- Yes. LeetCode 2061. Number of Spaces Cleaning Robot Cleaned is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.