Suppose we have one N x M binary matrix. Where 0 means empty cell and 1 means blocked cell. Now starting from the top left corner, we have to find the number of ways to reach the bottom right corner. If the answer is very large, mod it by 10^9 + 7.
So, if the input is like
0 | 0 | 1 |
0 | 0 | 0 |
1 | 1 | 0 |
then the output will be 2, as There are two ways to get to the bottom right: [Right, Down, Right, Down] and [Down, Right, Right, Down].
To solve this, we will follow these steps −
- dp := a matrix of same size of given matrix and fill with 0
- dp[0, 0] := 1
- for i in range 1 to row count of matrix, do
- if matrix[i, 0] is same as 1, then
- come out from loop
- otherwise,
- dp[i, 0] := 1
- if matrix[i, 0] is same as 1, then
- for j in range 1 to column count of matrix, do
- if matrix[0, j] is same as 1, then
- come out from the loop
- otherwise,
- dp[0, j] := 1
- if matrix[0, j] is same as 1, then
- for i in range 1 to row count of matrix, do
- for j in range 1 to column count of matrix, do
- if matrix[i, j] is same as 1, then
- dp[i, j] := 0
- otherwise,
- dp[i, j] := dp[i - 1, j] + dp[i, j - 1]
- if matrix[i, j] is same as 1, then
- for j in range 1 to column count of matrix, do
- return bottom right value of dp
Example (Python)
Let us see the following implementation to get better understanding −
class Solution: def solve(self, matrix): dp = [[0] * len(matrix[0]) for _ in range(len(matrix))] dp[0][0] = 1 for i in range(1, len(matrix)): if matrix[i][0] == 1: break else: dp[i][0] = 1 for j in range(1, len(matrix[0])): if matrix[0][j] == 1: break else: dp[0][j] = 1 for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i][j] == 1: dp[i][j] = 0 else: dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[-1][-1] ob = Solution() matrix = [ [0, 0, 1], [0, 0, 0], [1, 1, 0] ] print(ob.solve(matrix))
Input
matrix = [ [0, 0, 1], [0, 0, 0], [1, 1, 0] ]
Output
2