Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. Starting from the top-left cell, we need to reach the bottom-right cell. In one step, we can only move down or right. The score of a path is the sum of values in all cells on that path. We have to find the number of paths from start to end with score exactly k.
If there are many possible paths, we return the result modulo 10^9 + 7.
Example
Consider this matrix with k = 2:
| 0 | 0 | 1 |
| 1 | 0 | 1 |
| 0 | 1 | 0 |
The output will be 4, as there are 4 paths with score 2: [R,R,D,D], [D,R,R,D], [D,D,R,R], [D,R,D,R] where D means down and R means right.
Approach
We'll use a recursive approach with depth-first search (DFS):
- Start from position (0, 0) with initial score 0
- At each cell, add its value to the current score
- If we reach the destination with score k, count it as one valid path
- Explore both right and down directions recursively
Implementation
class Solution:
def solve(self, matrix, k):
m, n = len(matrix), len(matrix[0])
deno = 10**9 + 7
def dfs(i=0, j=0, pts=0):
# Check bounds
if i >= m or j >= n:
return 0
# Add current cell value to score
pts += matrix[i][j]
# If reached destination, check if score matches k
if i == m - 1 and j == n - 1:
return 1 if pts == k else 0
# Explore right and down directions
return dfs(i + 1, j, pts) + dfs(i, j + 1, pts)
return dfs() % deno
# Test the solution
ob = Solution()
matrix = [
[0, 0, 1],
[1, 0, 1],
[0, 1, 0]
]
k = 2
print(ob.solve(matrix, k))
4
How It Works
The algorithm works as follows:
- Base Case: If we go out of bounds, return 0 (no valid paths)
- Score Update: Add current cell value to the running score
- Destination Check: If we reach the bottom-right cell, return 1 if score equals k, otherwise 0
- Recursion: Try both possible moves (down and right) and sum their results
Optimized Version with Memoization
For better performance with larger matrices, we can use memoization:
class Solution:
def solve(self, matrix, k):
m, n = len(matrix), len(matrix[0])
deno = 10**9 + 7
memo = {}
def dfs(i, j, pts):
if (i, j, pts) in memo:
return memo[(i, j, pts)]
if i >= m or j >= n:
return 0
pts += matrix[i][j]
if i == m - 1 and j == n - 1:
result = 1 if pts == k else 0
else:
result = dfs(i + 1, j, pts) + dfs(i, j + 1, pts)
memo[(i, j, pts)] = result
return result
return dfs(0, 0, 0) % deno
# Test the optimized solution
ob = Solution()
matrix = [
[0, 0, 1],
[1, 0, 1],
[0, 1, 0]
]
k = 2
print(ob.solve(matrix, k))
4
Conclusion
The recursive DFS approach effectively counts all paths with the target score k. The memoized version improves performance by avoiding redundant calculations, making it suitable for larger matrices.
