Leetcode #2061: Number of Spaces Cleaning Robot Cleaned
In this guide, we solve Leetcode #2061 Number of Spaces Cleaning Robot Cleaned in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Matrix, Simulation
Intuition
Grid problems are easiest when you define clear row/column boundaries.
A consistent traversal order prevents off-by-one errors.
Approach
Iterate by rows, columns, or layers depending on the requirement.
Keep bounds updated as the traversal progresses.
Steps:
- Define bounds or directions.
- Visit cells in order.
- Update result and move bounds.
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 ans
Complexity
The time complexity is O(m·n). The space complexity is O(1) to O(m·n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.