659. Clear Diagonal Path
A cleaning robot must cross a rectangular warehouse floor described by grid with R rows and C columns. A cell holding 0 is clear and a cell holding 1 is blocked. The robot starts on the top-left cell (its dock) and wants to reach the bottom-right cell (the goal); these two cells are always usable, whatever value they hold. In one move it may step onto any of the eight neighbouring cells (up, down, left, right and the four diagonals), but only if that cell is clear.
Return the minimum number of moves needed to get from the top-left cell to the bottom-right cell. If no sequence of moves connects them, return -1. When the floor is a single clear cell the start is already the goal, so the answer is 0. Aim for O(R * C) time and space.
Example 1
- Input:
- grid = [[0,0,1],[1,1,0],[0,0,0]]
- Output:
- 3
- Explanation:
The robot steps right, then diagonally down-right onto the only clear cell of the middle row, then down into the corner: 3 moves.
Example 2
- Input:
- grid = [[0,1],[1,0]]
- Output:
- 1
- Explanation:
The start and the finish are diagonal neighbours and both are clear, so a single diagonal move is enough and the answer is 1.
Example 3
- Input:
- grid = [[0,1,1],[1,1,1],[1,1,0]]
- Output:
- -1
- Explanation:
Every neighbour of the start cell is blocked, so the robot cannot move at all and the answer is -1.
Constraints
1 ≤ R, C ≤ 350
grid[i][j] is 0 or 1; the values of the top-left and bottom-right cells are ignored
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 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms
Expected complexity
- Time
- O(R * C)
- Space
- O(R * C)