17

# 介绍

..the输出必须`315`

# 例子

``````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
6
``````

``````35 -7
-8 36
2
``````

2

@steveverrill。对于这个挑战，时间上的复杂性不算什么，但是如果您回答这个问题并证明您的方法比暴力破解有效，我将很乐意赞成您的回答。

Answers:

4

# JavaScript（ES6），190字节

``(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``

## 说明

``````(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``````

## 测试

``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>``````

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.