Number of Spaces Cleaning Robot Cleaned — LeetCode 2061 Python Solution

MediumLeetCode PremiumArrayMatrixSimulation
Problem
#2061
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

Python
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

MeasureComplexity
TimeO(m·n)
SpaceO(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.

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.

Get Stealth Interview