Program to find number of ways we can reach from top left point to bottom right point in Python

PythonServer Side ProgrammingProgramming

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

001
000
110

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
  • 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
  • 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]
  • return bottom right value of dp

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

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
raja
Published on 12-Dec-2020 10:14:51
Advertisements