This problem simulates the movement of a cleaning robot in a room represented by a binary matrix. The robot starts at (0,0) facing right and cleans spaces until it encounters an obstacle or a room boundary. The goal is to determine the total number of clean spaces.
Both solutions presented use Depth-First Search (DFS) or a similar iterative approach to track the robot's movement and count cleaned spaces. The key differences lie in how they handle visited cells and the overall approach.
Solution 1 (DFS):
This solution uses a recursive DFS function.
dfs(i, j, k)
: This function takes the current row (i
), column (j
), and direction (k
) as input. k
represents the direction (0: right, 1: down, 2: left, 3: up).vis
: A set to keep track of visited cells to prevent infinite loops. The tuple (i, j, k)
uniquely identifies a cell and its direction.dirs
: An array to efficiently determine the next cell's coordinates based on the current direction.vis
, it returns (avoiding cycles).ans
if the cell is clean (value 0).room
matrix.dfs
for the next cell. Otherwise, it turns clockwise (updates k
) and recursively calls dfs
from the current cell.Solution 2 (Iterative):
This solution uses an iterative approach with a while
loop, mimicking the robot's movement.
dirs
: Same as in Solution 1.vis
: A 3D boolean array (m x n x 4) to track visited states. This is slightly less efficient in terms of space than using a set in Solution 1, especially for larger matrices, but it might be faster in access.while
loop continues as long as the current cell and direction have not been visited.vis
.ans
if the cell is clean.room
(set to -1).Time Complexity Analysis:
Both solutions visit each cell at most once in each of the four directions. In the worst case, the robot visits each cell exactly four times (once for each direction). Therefore, the time complexity is O(m*n), where 'm' is the number of rows and 'n' is the number of columns in the room matrix.
Space Complexity Analysis:
vis
set, which might store up to all cells and directions. However, if there are many obstacles, significantly less space might be used.vis
array. This is generally larger than the set in Solution 1, unless most cells are visited in all four directions.Code Examples (Python):
Solution 1 (DFS) provides a cleaner and slightly more memory-efficient solution if many cells are not explored in all directions. Solution 2's iterative approach might be faster in some implementations but uses more memory in general. The choice depends on the priorities (memory vs speed). Both are valid solutions to the problem.