1. Description
An m x n binary grid contains empty cells (0) and mirrors (1).
A robot travels from (0,0) to (m - 1,n - 1), choosing right or down moves at empty cells.
Trying to enter a mirror while moving right redirects the robot to the cell below the mirror. Trying to enter one while moving down redirects it to the cell to the mirror’s right.
If that cell is another mirror, continue reflecting according to the arrival direction. Discard any route that leaves the grid.
Return the number of distinct valid paths modulo 10$^9$ + 7.
2. Example
Example 1
Input: grid = [[0,1,0],[0,0,1],[1,0,0]]
Output: 5
Explanation: Two valid routes begin by moving right, and three begin by moving down.
Example 2
Input: grid = [[0,0],[0,0]]
Output: 2
Explanation: With no mirrors, the two routes are right then down and down then right.
Example 3
Input: grid = [[0,1,1],[1,1,0]]
Output: 1
Explanation: Moving right triggers reflections at (0,1) and (1,1), reaching (1,2). Moving down instead eventually sends the robot outside the grid.
3. Constraints
- m == grid.length
- n == grid[i].length
- 2 <= m, n <= 500
- grid[i][j] is either 0 or 1.
- grid[0][0] == grid[m - 1][n - 1] == 0
4. Solutions
Dynamic Programming
m = grid.size(), n = grid.front().size()
Time complexity: O(mn)
Space complexity: O(n)
| |