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 find number of coins we can pick from topleft to bottom-right cell and return in Python
This problem involves finding the maximum coins we can collect by making two simultaneous journeys: one from top-left to bottom-right, and another from bottom-right back to top-left. We can only move right or down in the first journey, and left or up in the return journey.
Problem Understanding
The matrix contains three types of values:
0 for an empty cell
1 for a coin
?1 for a wall (impassable)
We need to maximize coin collection while ensuring we can complete both journeys. If either path is blocked, we return 0.
Example
Consider this matrix:
| 0 | 1 | 1 |
| 1 | 1 | 1 |
| 1 | ?1 | 1 |
| 0 | 1 | 1 |
The optimal path collects 8 coins total.
Solution Approach
We use dynamic programming with memoization to solve this problem. The key insight is to track two paths simultaneously using four coordinates (i, j, k, l) representing the positions of both journeys.
class Solution:
def solve(self, mat):
n, m = len(mat), len(mat[0])
def util(i, j, k, l):
# Check if positions are valid and not walls
if not (0 <= i < n and 0 <= j < m) or mat[i][j] == -1:
return -1e9
if not (0 <= k < n and 0 <= l < m) or mat[k][l] == -1:
return -1e9
# Base case: reached starting position
if i == 0 and j == 0 and k == 0 and l == 0:
return mat[0][0]
best = -1e9
# Try all possible moves for both paths
for dx1, dy1 in [(-1, 0), (0, -1)]:
for dx2, dy2 in [(-1, 0), (0, -1)]:
best = max(best, util(i + dy1, j + dx1, k + dy2, l + dx2))
# Collect coins from current positions
# Avoid double counting if both paths are at same position
return mat[i][j] + (i != k) * mat[k][l] + best
return max(0, util(n - 1, m - 1, n - 1, m - 1))
# Test the solution
ob = Solution()
matrix = [
[0, 1, 1],
[1, 1, 1],
[1, -1, 1],
[0, 1, 1]
]
print(ob.solve(matrix))
8
How It Works
The algorithm works by:
Recursive exploration: Starting from the bottom-right corner, we explore all valid paths backwards
Coordinate tracking: We track two paths simultaneously using (i,j) and (k,l) coordinates
Boundary checking: We validate that positions are within bounds and not walls
Coin collection: We sum coins from both positions, avoiding double-counting when paths overlap
Optimization: We return the maximum coins possible, or 0 if no valid path exists
Time Complexity
The time complexity is O(n²m²) where n and m are the matrix dimensions, as we explore all possible combinations of positions for both paths.
Conclusion
This dynamic programming solution efficiently finds the maximum coins collectible in a round trip through the matrix. The key insight is tracking two simultaneous paths and avoiding double-counting when they overlap.
