JavaScript (ES6), 190 byte
(m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o
Spiegazione
Prende la matrice come una matrice di array.
Inizia da ogni quadrato quindi utilizza una funzione ricorsiva per testare ogni possibile combinazione. Questo è un approccio a forza bruta, ma termina quasi all'istante per il primo caso di test sulla mia macchina.
(m,n)=>
m.map((a,r)=> // for each row
a.map((_,c)=> // for each column
f(r,c,[0],0) // start checking paths from the coordinate of the square
),
o= // o = output number (max total)
f=(x,y,s,t)=> // recursive function f, x & y = current square, t = total
// s = array of used squares (starts as [0] so length = +1)
s[n]? // if we have used n squares
o>t?0:o=t // set o to max of o and t
:s.indexOf(w=x+","+y)<0&& // if the square has not been used yet
m[y]&&(v=m[y][x])<1/0&& // and the square is not out of bounds
// ( if value of square is less than Infinity )
// Check each adjacent square
f(x+1,y,
s=[...s,w], // clone and add this square to s
t+=v // add the value of this square to the total
)
+f(x,y+1,s,t)
+f(x-1,y,s,t)
+f(x,y-1,s,t)
)
|o // return output
Test
var solution = (m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o
<textarea rows="7" cols="40" id="Matrix">10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20</textarea><br />
N = <input type="number" id="N" value="6" /><br />
<button onclick="result.textContent=solution(Matrix.value.split('\n').map(x=>x.split(' ').map(z=>+z)),N.value)">Go</button>
<pre id="result"></pre>