Program to count number of paths with cost k from start to end point in Python


Suppose we have a 2d binary matrix and another value k. Now starting from the top-left cell, we have to go to the bottom right cell. In one step, we can only go down, or right. Now the score of a path is the sum of the values on the cells on the path. We have to find the number of paths from the start cell to end cell with score k. If there are huge possible ways then return result mod 10^9+7.

So, if the input is like

001
101
010

K = 2, then the output will be 4, as the paths with score 2 are [R,R,D,D], [D,R,R,D], [D,D,R,R], [D,R,D,R] here D is down and R is right.

To solve this, we will follow these steps −

  • deno := 10^9 + 7

  • m := row count of matrix, n := column count of matrix

  • Define a function dfs() . This will take i, j, pts

  • if i >= m or j >= n, then

    • return 0

  • pts := pts + matrix[i, j]

  • if i is same as m - 1 and j is same as n - 1, then

    • return 1 when pts is same as k otherwise 0

  • return dfs(i + 1, j, pts) + dfs(i, j + 1, pts)

  • From the main method do the following −

  • return dfs(0, 0, 0) mod deno

Example 

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, matrix, k):
      m, n = len(matrix), len(matrix[0])
      def dfs(i=0, j=0, pts=0):
         if i >= m or j >= n:
            return 0
         pts += matrix[i][j]
         if i == m - 1 and j == n - 1:
            return int(pts == k)
         return dfs(i + 1, j, pts) + dfs(i, j + 1, pts)
      return dfs() % (10 ** 9 + 7)

ob = Solution()
matrix = [
   [0, 0, 1],
   [1, 0, 1],
   [0, 1, 0]
]
k = 2
print(ob.solve(matrix, k))

Input

[
   [0, 0, 1],
   [1, 0, 1],
   [0, 1, 0]
], 2

Output

4

Updated on: 22-Dec-2020

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements