I have a n*n matrix, where each element represents an integer. Starting in [0,0] I have to find the path of exactly m elements down to the last row, returning the maximum cost. The path can end in any column on the last row and n ≤ m ≤ n^2
I thought of finding all paths of length m from [0,0] to [n-1, 0], [n-1, 1] ... [n-1, n-1]. But it does not feel optimal…
Which algorithm would be the most efficient way of doing this? BFS or DFS?
EDIT
Possible directions are down/right/left, but only visit each element at most once.
EDIT 2
So for example, if this matrix is given (n=4):
[ 1 4 1 20 ]
[ 5 0 2 8 ]
[ 6 8 3 8 ]
[ 3 2 9 5 ]
And m=7, the path could be
[ → → → ↓ ]
[ 5 0 2 ↓ ]
[ 6 8 3 ↓ ]
[ 3 2 9 x ] = Path cost = 47
or
[ ↓ 4 1 20 ]
[ ↓ 0 2 8 ]
[ → → ↓ 8 ]
[ 3 2 → x ] = Path cost = 32
or if m = n^2
[ → → → ↓ ]
[ ↓ ← ← ← ]
[ → → → ↓ ]
[ x ← ← ← ]
EDIT 3 / SOLUTION
Thanks to Wanderley Guimarães,
http://ideone.com/0iLS2
You can solve this problem with dynamic programming. Let
value(i, j)the value from position(i, j)of your matrix (i-th line, j-th column).That recurrence assume that you use a position from your matrix when you step down. So, you answer is
max(f(m, 0), f(m-1, 1), f(m - 2, 2), ..., f(1, m)).For example:
Give the follow matrix for
n = 4:If
m = 2then you cant go after second line. And you answer isf(2, 2) = 4.If
m = 4then you cant go after third line. And you answer isf(3, 2) = 5.(Im learning english so If you didnt understand something let me know and I will try to improve my explanation).
Edit :: allow down/left/right moves
You can implement follow recurrence:
This solution is
O(n^4). Im trying to improve it.You can test it at http://ideone.com/tbH1j