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
This is actually a DAG, and therefore the dynamic programming solution to the longest path problem works.
Why a DAG, you say? There is an obvious cycle going from two vertices that are horizontally adjacent. If you use the "obvious" graph, of course.
The less obvious approach is to rework this as a graph of (vertex, direction), in which direction is the last direction you took from down/left/right. A vertex that has direction down can go either down, left, or right, whereas a vertex with direction right can only go down/right, and a vertex with direction left can only go left/down. This graph is clearly acyclic, and it comprises all possible paths in the original matrix.
Therefore, ignoring the limit m, a possible recursion for the longest path to (a, b, direction) is
pdl[i][j] = max(pdl[i][j-1], pd[i-1][j])+arr[i][j]; pdr[i][j] = max(pdr[i][j+1], pd[i-1][j])+arr[i][j]; pd[i][j] = max(pdl[i][j], pdr[i][j]);
pd is the array for the "down" vertices, pdr for right and pdl is for left. As an implementation detail, note that I keep the max of the left and corresponding down vertex in pdl, but this doesn't really matter as any vertex with direction "down" can go left and down just as a "left" vertex would. Same for pdr.
The limit means you'll have to add another dimension to that DP solution, that is, you have to keep pd[i][j][moves], that keeps the highest sum possible until vertex (i, j) using exactly moves movements, obtaining the recursion
pdl[i][j][moves] = max(pdl[i][j-1][moves-1], pd[i-1][j][moves-1])+arr[i][j]; pdr[i][j][moves] = max(pdr[i][j+1][moves-1], pd[i-1][j][moves-1])+arr[i][j]; pd[i][j][moves] = max(pdl[i][j][moves-1], pdr[i][j][moves-1]);