MediumNo. 2061LeetCode Premium

Number of Spaces Cleaning Robot Cleaned — LeetCode 2061 Python Solution

Topics
Array, Matrix, Simulation
Reading time
4 min

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

PythonSolution
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

Time
O(m·n)
Space · auxiliary
O(1) to O(m·n)

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

Related problems
No.ProblemDifficulty
0054Spiral MatrixMedium
0059Spiral Matrix IIMedium
0289Game of LifeMedium
0498Diagonal TraverseMedium
0566Reshape the MatrixEasy
0867Transpose MatrixEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.