1150. Wall-Turning Robot
A cleaning robot roams a grid where '.' is open floor and '#' is a wall. It starts at row 0, column 0 facing east, and the start cell counts as open floor whatever it holds. Each step, if the cell in front of it is inside the grid and open, the robot moves into that cell. Otherwise it turns 90 degrees clockwise on the spot, and that turn uses up the step. Clockwise, the directions are east, south, west, north. Given the grid and the number of steps, return [row, col] for the cell where the robot stands after exactly that many steps.
m * n <= 10^5 and 0 <= steps <= 10^15, so direct simulation is too slow. The state (row, column, direction) must repeat: record the first step of each state, skip whole cycles and simulate only the remainder. This takes O(m * n) time and space.
Example 1
- Input:
- grid = [[".",".","."]], steps = 4
- Output:
- [0,2]
- Explanation:
The robot walks to column 2 in two steps, then turns south (outside the grid) and turns west on step 4, still standing at [0, 2].
Example 2
- Input:
- grid = [[".",".","#"],[".","#","."],[".",".","."]]steps = 3
- Output:
- [0,1]
- Explanation:
The robot moves to column 1 on step 1. The wall ahead makes it turn south on step 2, and the wall below makes it turn west on step 3, so it stays at [0, 1].
Example 3
- Input:
- grid = [["."]], steps = 100000
- Output:
- [0,0]
- Explanation:
In a 1 x 1 grid the robot only turns, so it always stays at [0, 0].
Constraints
1 ≤ m, n and m * n ≤ 105
0 ≤ steps ≤ 1015
grid[i][j] is '.' or '#'
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(m * n)
- Space
- O(m * n)