Suppose we have a 2D matrix where matrix [r, c] represents the number of coins in that cell. We can start from any position and want to collect coins by moving any of the four directions (up, down, left and right, not diagonally). When we move to a cell the coins are collected and the value of that cell becomes 0. We cannot visit a cell with 0 coins, we have to find the maximum amount of coins we can collect.
So, if the input is like
2 | 4 | 3 |
3 | 6 | 0 |
2 | 0 | 12 |
then the output will be 18, as we can take the path 2 −> 3 −> 6 −> 4 −> 3
To solve this, we will follow these steps −
if matrix is empty, then
return 0
n := row count of matrix, m := column count of mat
x := a list like [−1, 1, 0, 0], y := a list like [0, 0, −1, 1]
Define a function util() . This will take a, b
ret := 0
for k in range 0 to 3, do
(t1, t2) := (x[k] + a, y[k] + b)
if (t1, t2) is valid cell, then
t := mat[t1, t2], mat[t1, t2] := 0
ret := maximum of ret and (util(t1, t2) + t)
mat[t1, t2] := t
return ret
From the main method do the following −
res := 0
for i in range 0 to n − 1, do
for j in range 0 to m − 1, do
if mat[i, j] is non−zero, then
t := mat[i, j], mat[i, j] := 0
res := maximum of res and (util(i, j) + temp)
return res
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, mat): if not mat: return 0 n, m = len(mat), len(mat[0]) x, y = [−1, 1, 0, 0], [0, 0, −1, 1] def ok(a, b): return 0 <= a < n and 0 <= b < m and mat[a][b] def util(a, b): ret = 0 for k in range(4): t1, t2 = x[k] + a, y[k] + b if ok(t1, t2): t, mat[t1][t2] = mat[t1][t2], 0 ret = max(ret, util(t1, t2) + t) mat[t1][t2] = t return ret res = 0 for i in range(n): for j in range(m): if mat[i][j]: temp, mat[i][j] = mat[i][j], 0 res = max(res, util(i, j) + temp) return res ob = Solution() matrix = [ [2, 4, 3], [3, 6, 0], [2, 0, 12] ] print(ob.solve(matrix))
Input
[ [2, 4, 3], [3, 6, 0], [2, 0, 12] ]
Output
18