[Question]
  [
Sixteen piles of cheese are put on a 4x4 square. They're labeled from \$1\$ to \$16\$. The smallest pile is \$1\$ and the biggest one is \$16\$.
The Hungry Mouse is so hungry that it always goes straight to the biggest pile (i.e. \$16\$) and eats it right away.
After that, it goes to the biggest neighboring pile and quickly eats that one as well. (Yeah ... It's *really* hungry.) And so on until there's no neighboring pile anymore.
A pile may have up to 8 neighbors (horizontally, vertically and diagonally). There's no wrap-around.
## Example
We start with the following piles of cheese:
$$\begin{matrix}
3&7&10&5\\
6&8&12&13\\
15&9&11&4\\
14&1&16&2
\end{matrix}$$
The Hungry Mouse first eats \$16\$, and then its biggest neighbor pile, which is \$11\$.
$$\begin{matrix}
3&7&10&5\\
6&8&12&13\\
15&9&üê≠&4\\
14&1&\color{grey}\uparrow&2
\end{matrix}$$
Its next moves are \$13\$, \$12\$, \$10\$, \$8\$, \$15\$, \$14\$, \$9\$, \$6\$, \$7\$ and \$3\$ in this exact order.
$$\begin{matrix}
üê≠&\color{grey}\leftarrow&\small\color{grey}\swarrow&5\\
\small\color{grey}\nearrow&\small\color{grey}\swarrow&\color{grey}\uparrow&\color{grey}\leftarrow\\
\color{grey}\downarrow&\small\color{grey}\nwarrow&\small\color{grey}\nearrow&4\\
\small\color{grey}\nearrow&1&\color{grey}\uparrow&2
\end{matrix}$$
There's no cheese anymore around the Hungry Mouse, so it stops there.
## The challenge
Given the initial cheese configuration, your code must print or return the sum of the remaining piles once the Hungry Mouse has stopped eating them.
For the above example, the expected answer is \$12\$.
## Rules
* Because the size of the input matrix is fixed, you may take it as either a 2D array or a one-dimensional array.
* Each value from \$1\$ to \$16\$ is guaranteed to appear exactly once.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
```
[ [ 4,  3,  2,  1], [ 5,  6,  7,  8], [12, 11, 10,  9], [13, 14, 15, 16] ] --> 0
[ [ 8,  1,  9, 14], [11,  6,  5, 16], [13, 15,  2,  7], [10,  3, 12,  4] ] --> 0
[ [ 1,  2,  3,  4], [ 5,  6,  7,  8], [ 9, 10, 11, 12], [13, 14, 15, 16] ] --> 1
[ [10, 15, 14, 11], [ 9,  3,  1,  7], [13,  5, 12,  6], [ 2,  8,  4, 16] ] --> 3
[ [ 3,  7, 10,  5], [ 6,  8, 12, 13], [15,  9, 11,  4], [14,  1, 16,  2] ] --> 12
[ [ 8,  9,  3,  6], [13, 11,  7, 15], [12, 10, 16,  2], [ 4, 14,  1,  5] ] --> 34
[ [ 8, 11, 12,  9], [14,  5, 10, 16], [ 7,  3,  1,  6], [13,  4,  2, 15] ] --> 51
[ [13, 14,  1,  2], [16, 15,  3,  4], [ 5,  6,  7,  8], [ 9, 10, 11, 12] ] --> 78
[ [ 9, 10, 11, 12], [ 1,  2,  4, 13], [ 7,  8,  5, 14], [ 3, 16,  6, 15] ] --> 102
[ [ 9, 10, 11, 12], [ 1,  2,  7, 13], [ 6, 16,  4, 14], [ 3,  8,  5, 15] ] --> 103
```
  
[Answer]
# [Python 2](https://docs.python.org/2/), ~~133~~ 130 bytes
```
a=input();m=16
for i in range(m):a[i*5:i*5]=0,
while m:i=a.index(m);a[i]=0;m=max(a[i+x]for x in[-6,-5,-4,-1,1,4,5,6])
print sum(a)
```
[Try it online!](https://tio.run/##hVDbboMwDH3nK/JW6EJFQpJCK74E8RBtbI00AqKtyr6emdil21RpEiSycy4@Hr4up97L2frzrR3PrGJ1xhl8grMcTgmX4kxDuS@gzuRy5E3UTu3rZrOZbeX8cL3EybGrhIne@5E55jwbrf9o4y452Npt9QH@psp4dDu5z5Z1B1fZnfNv7QSQI0DgEQQ6O8VQvEzNojOBTp0anmqeKp4KLrjimpsmiYbR@Qs7X7vYJjMWlGA39EOcJRHMthXZXKuQQ4ZAmjMDOTgrMJkQSxjOSriWsIAVgBGmieoiMErqisAMb4TVQXSPArQpBTwR@tBQv/1KRAZL@cQvPOqHXYmqaJGjtwx6Mugp4uXrEOhW/NDXaCsQrYLcEkBiPrS4ByIr8gnjoNmDq2kvlIGWox/o/X1oElW4@YW3BsaWQat/9gS8v3tbR8rvDFpajqqG/J7yaJcGoWolkopuvgE "Python 2 ‚Äì Try It Online")
Takes a flattened list of 16 elements.
### How it works
```
a=input();m=16
# Add zero padding on each row, and enough zeroes at the end to avoid index error
for i in range(m):a[i*5:i*5]=0,
# m == maximum element found in last iteration
# i == index of last eaten element
# eaten elements of `a` are reset to 0
while m:i=a.index(m);a[i]=0;m=max(a[i+x]for x in[-6,-5,-4,-1,1,4,5,6])
print sum(a)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 111 bytes
```
i=x=a=input()
while x:x,i=max((y,j)for j,y in enumerate(a)if i>[]or 2>i/4-j/4>-2<i%4-j%4<2);a[i]=0
print sum(a)
```
[Try it online!](https://tio.run/##jVTLbtswELzzKxYuAkiAjIgPSa4T@UcEHVRHQWjEsiHZiJyfd3eXj9ht0fZAQFwOZ4azpI6X09thUNft4aWvF4vF1dZz3dV2OJ5PSSo@3ux7D/N6zmy97@YkuWS79PUwwi67gB2gH877fuxOfdKl9hXspmlxUW3so1nuHs1mqZ7tA34@mGeVPnWNbetcHEc7nGA673HTFTWF2HZTP0ENjWigAZMBaBwKh2wzrBT4VeKocKyoInFNShw5Vr5zBXdI3CkRK8sW2uwbLJcbyJlyRVQEJRDDpad08EBQeNmKK7kzQmJgfqWUHqp58Y8uWS73TtXfXEqiZGjhATIQsICMnrT3TNLsm03Q@cw9pWaX2vnhoxQMLx2cE9RMWfhgZDgJGSBJSVh141LFMIOxr@ikVypif/LIkLmuBl508mXTBE6XUuyn8QfNQ4M41xBG1OXbolg3chYuTn2j6NIvfYv/v2eRs1qxz986Gu@BCXk6Lu/eqWifRHnvU@bqH6RVJC09hbkljTJ3pFq0ohumj37kN4XMRJ6Fq6yRosBpRZnn3CjdCnrU9AwzcFvpdX/aY8JPMxSndC2gG0einYG2MI4wPJtpNrYC@P@BqPdu/@OlW@MWAf3cb4H@M9ef "Python 2 ‚Äì Try It Online")
Method and test cases adapted from [Bubbler](https://codegolf.stackexchange.com/a/176257/20260). Takes a flat list on STDIN.
The code checks whether two flat indices `i` and `j` represent touching cells by checking that both row different `i/4-j/4` and column difference `i%4-j%4` are strictly between -2 and 2. The first pass instead has this check automatically succeed so that the largest entry is found disregarding adjacency.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~50~~ ~~49~~ 47 bytes
```
16:HZ^!"2G@m1ZIm~]v16eXK68E16b"Ky0)Y)fyX-X>h]s-
```
Input is a matrix, using `;` as row separator.
[Try it online!](https://tio.run/##y00syfn/39DMyiMqTlHJyN0h1zDKM7cutszQLDXC28zC1dAsScm70kAzUjOtMkI3wi4jtlj3//9oYx0Fcx0FQwMdBVNrBTMdBQsgxwiIja0VDE11FCyBTEMdBRMgzwTIBCKgGqNYAA) Or [verify all test cases](https://tio.run/##hZA/a8MwEMX3foprtoAMPluS7QhCh5YkZM3g2iikhZQO8dRSmqVf3bk/ciAQ6GAZnd57v7sb3r5P42FEv1h3@8dZsXoasNsMf/EH/bHd@voF/ftse87nr/OPc5u1y8/4lY3P3e9u7K2B0kBhAAM4A95AZaAOgFxC@nIDDV1JhKRF0qCPD31Nf3rhahAhOeUtaZ2EVkECuEA3Sz6UOhXsLa9RlCCLOzx5dKmIoi@lhUrFThGEp5Oas8lXCoDdLjCtVh2WQeIaRfIMVuKQNIXOp4hpINQgl1aTJ2kQknpd2gsqo9FQN6kDB2jTKdTq5tl3HVgyOZrb@2dP8QI).
### Explanation
```
16:HZ^!  % Cartesian power of [1 2 ... 16] with exponent 2, transpose. Gives a 
         % 2-row matrix with 1st column [1; 1], 2nd [1; 2], ..., last [16; 16] 
"        % For each column, say [k; j]
  2      %   Push 2
  G@m    %   Push input matrix, then current column [k; j], then check membership.
         %   This gives a 4√ó4 matrix that contains 1 for entries of the input that
         %   contain k or j 
  1ZI    %   Connected components (based on 8-neighbourhood) of nonzero entries.
         %   This gives a 4√ó4 matrix with each connected component labeled with
         %   values 1, 2, ... respectively
  m~     %   True if 2 is not present in this matrix. That means there is only
         %   one connected component; that is, k and j are neighbours in the
         %   input matrix, or k=j
]        % End
v16e     % The stack now has 256 values. Concatenate them into a vector and
         % reshape as a 16√ó16 matrix. This matrix describes neighbourhood: entry 
         % (k,j) is 1 if values k and j are neighbours in the input or if k=j
XK       % Copy into clipboard K
68E      % Push 68 times 2, that is, 136, which is 1+2+...+16
16       % Push 16. This is the initial value eaten by the mouse. New values will
         % be appended to create a vector of eaten values
b        % Bubble up the 16√ó16 matrix to the top of the stack
"        % For each column. This just executes the loop 16 times
  K      %   Push neighbourhood matrix from clipboard K
  y      %   Copy from below: pushes a copy of the vector of eaten values
  0)     %   Get last value. This is the most recent eaten value
  Y)     %   Get that row of the neighbourhood matrix
  f      %   Indices of nonzeros. This gives a vector of neighbours of the last
         %   eaten value
  y      %   Copy from below: pushes a copy of the vector of eaten values
  X-     %   Set difference (may give an empty result)
  X>     %   Maximum value. This is the new eaten value (maximum neighbour not
         %   already eaten). May be empty, if all neighbours are already eaten
  h      %   Concatenate to vector of eaten values
]        % End
s        % Sum of vector of all eaten values
-        % Subtract from 136. Implicitly display
```
[Answer]
# PHP, ~~177 174~~ 171 bytes
```
for($v=16;$v;$u+=$v=max($p%4-1?max($a[$p-5],$a[$p-1],$a[$p+3]):0,$a[$p-4],$a[$p+4],$p%4?max($a[$p-3],$a[$p+1],$a[$p+5]):0))$a[$p=array_search($v,$a=&$argv)]=0;echo 120-$u;
```
Run with `-nr`, provide matrix elements as arguments or [try it online](http://sandbox.onlinephpfunctions.com/code/c119f93dedfb54eeb4273062815523e07a41f22d).
[Answer]
# JavaScript, 122 bytes
I took more than a couple of wrong turns on this one and now I've run out of time for further golfing but at least it's working. Will revisit tomorrow (or, knowing me, on the train home this evening!), if I can find a minute.
```
a=>(g=n=>n?g([-6,-5,-4,-1,1,4,5,6].map(x=>n=a[x+=i]>n?a[x]:n,a[i=a.indexOf(n)]=n=0)|n)-n:120)(16,a=a.flatMap(x=>[...x,0]))
```
[Try it online](https://tio.run/##jVPLbtswELznK3iUYErhig@7AeTeCzQ59KgKMJNYhgKXCmKjUIH8u7tcPqogKdrDAsRydmY4Kz3Zn/b08DI@n6t7e78/Vm563F@G9mLbbXFoXbt1nw9FVxleaV4pXgEHrrjmpq9/2OdiRkBru3nVjj1C8dTfOG67sbX16B73891QuLJHIlG@urJyN9CIsgDDLSKGoz1/DSxdXdczF31ZXh4md5qO@/o4ofJVxzqmOGMSq8GCnmNH48lgrbE2vgN4B4AlsPOJOjgBOAmIBdMz7F1fM0GEG0/kgR5CYIiEAZzGdRRdU0cEG16KqbeEEIGSrj50SGIiumz@7hA8IQF1vIY0TvSQ/cjo1wuTZ7Lg36aWhJIcyuCFHqEJbAKYkpNEqGMkkF7h5b0geGyTHTY5xGTqT2QQdXTeisjzPOwysaKPZFElxpBO3qGKTxRpLZRniiGr0hfSkGpk1CFGuVALmZu41v/fVGRcb8jjuy3m3auUY2CKzoOGjBmYpUcQzT8o15nSRAK1pMwiC0p5lf/ML9/ubuvT@WV0h3H4VczlasfaLdutBjyX9dM0ut13tysvvwE)
[Answer]
# Powershell, ~~143~~ ~~141~~ ~~136~~ ~~130~~ ~~122~~ 121 bytes
```
$a=,0*5+($args|%{$_+0})
for($n=16;$i=$a.IndexOf($n)){$a[$i]=0
$n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1]}$a|%{$s+=$_}
$s
```
Less golfed test script:
```
$f = {
$a=,0*5+($args|%{$_+0})
for($n=16;$i=$a.IndexOf($n)){
    $a[$i]=0
    $n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1]
}
$a|%{$s+=$_}
$s
}
@(
    ,( 0  , ( 4,  3,  2,  1), ( 5,  6,  7,  8), (12, 11, 10,  9), (13, 14, 15, 16) )
    ,( 0  , ( 8,  1,  9, 14), (11,  6,  5, 16), (13, 15,  2,  7), (10,  3, 12,  4) )
    ,( 1  , ( 1,  2,  3,  4), ( 5,  6,  7,  8), ( 9, 10, 11, 12), (13, 14, 15, 16) )
    ,( 3  , (10, 15, 14, 11), ( 9,  3,  1,  7), (13,  5, 12,  6), ( 2,  8,  4, 16) )
    ,( 12 , ( 3,  7, 10,  5), ( 6,  8, 12, 13), (15,  9, 11,  4), (14,  1, 16,  2) )
    ,( 34 , ( 8,  9,  3,  6), (13, 11,  7, 15), (12, 10, 16,  2), ( 4, 14,  1,  5) )
    ,( 51 , ( 8, 11, 12,  9), (14,  5, 10, 16), ( 7,  3,  1,  6), (13,  4,  2, 15) )
    ,( 78 , (13, 14,  1,  2), (16, 15,  3,  4), ( 5,  6,  7,  8), ( 9, 10, 11, 12) )
    ,( 102, ( 9, 10, 11, 12), ( 1,  2,  4, 13), ( 7,  8,  5, 14), ( 3, 16,  6, 15) )
    ,( 103, ( 9, 10, 11, 12), ( 1,  2,  7, 13), ( 6, 16,  4, 14), ( 3,  8,  5, 15) )
) | % {
    $expected, $a = $_
    $result = &$f @a
    "$($result-eq$expected): $result"
}
```
Output:
```
True: 0
True: 0
True: 1
True: 3
True: 12
True: 34
True: 51
True: 78
True: 102
True: 103
```
Explanation:
**First**, add top and bottom borders of 0 and make a single dimensional array:
```
0 0 0 0 0
# # # # 0
# # # # 0
# # # # 0
# # # # 0
     ‚Üì
0 0 0 0 0 # # # # 0 # # # # 0 # # # # 0 # # # # 0
```
Powershell returns `$null` if you try to get the value behind the end of the array.
**Second**, loop `biggest neighbor pile` started from 16 to non-zero-maximum. And nullify it (The Hungry Mouse eats it).
```
for($n=16;$i=$a.IndexOf($n)){
    $a[$i]=0
    $n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1]
}
```
**Third**, sum of the remaining piles.
[Answer]
# [R](https://www.r-project.org/), ~~128~~ ~~124~~ ~~123~~ ~~112~~ 110 bytes
```
function(r){r=rbind(0,cbind(0,r,0),0)
m=r>15
while(r[m]){r[m]=0
m=r==max(r[which(m)+c(7:5,1)%o%-1:1])}
sum(r)}
```
[Try it online!](https://tio.run/##LU3LCsIwELz3K7wUNjiFbB9Wi/FHpIcaLQ2YFtYWC9JvjxGEZYZ5MCuh352z0C@jnd00kqiPGLm58U4a9s8CreIl3siFq@Q9uOeD5OrbWI5o9C8xxndrdGNqB/Jqb6luKrBKpzTjhlu1Ja/Fxw9b6Ml3s7iVLJ3AGszgHIwcNbjAAXxACS5R4Ii4UakoS6XCFw "R ‚Äì Try It Online")
It creates a 4x4 matrix (which helped me to visualize things), pads it with 0's, then begins from 16 and searches it's surrounding "piles" for the next largest, and so forth.
Upon conclusion, it does output a warning, but it is of no consequence and does not change the result.
**EDIT:** -4 bytes by compressing the initialization of the matrix into 1 line.
**EDIT:** -1 thanks to Robert Hacken
**EDIT:** -13 bytes combining Giuseppe and Robin Ryder's suggestions.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
Ôº•Ôº°‚≠ÜŒπ¬ßŒ±Œª‚âîQŒ∏Ôº∑‚Ä∫Œ∏A¬´‚âî‚åïÔº´Ôº°Œ∏Œ∏Ôº™Ôπ™Œ∏‚Å¥√∑Œ∏‚Å¥‚âî‚åàÔº´Ôº≠Œ∏A¬ª‚âîŒ£Ôº•Ôº´Ôº°‚åïŒ±ŒπŒ∏‚éöÔº©Œ∏
```
[Try it online!](https://tio.run/##TU9Na8MwDD03v0LkJIMHTZvug55Cx0YGgY7uVnowjWlNHTtxnK4w9tszOWlgFkbS89N71vEs3NEK3fdbp4zHQtSYm7rzyDjsPGGnACkOmc9NKW8oOGhGZx1lbatOBuPPmEND/fdZaQn47qTw0mHDIc5ixuAnmt2pb8qUuJXykmkdDBo2Ts4@uqr@sljYstM2TKb0khv/qq6qlCMQeHedQtxU1VWDVGGtk8gmpXGNYLyOfqcv7ogb1vhnPXyFdlFsGt1oKRxSMUpsROuxIde@30OIJQd44pDMKa8OnJBHqp4JWdBdBiRZEfJCXUI5HZCUKuqSwF0cgKJ/uOo/ "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation:
```
Ôº•Ôº°‚≠ÜŒπ¬ßŒ±Œª
```
Convert the input numbers into alphabetic characters (A=0 .. Q=16) and print them as a 4x4 grid.
```
‚âîQŒ∏
```
Start by eating the Q, i.e. 16.
```
Ôº∑‚Ä∫Œ∏A¬´
```
Repeat while there is something to eat.
```
‚âî‚åïÔº´Ôº°Œ∏Œ∏
```
Find where the pile is. This is a linear view in row-major order.
```
Ôº™Ôπ™Œ∏‚Å¥√∑Œ∏‚Å¥
```
Convert to co-ordinates and jump to that location.
```
‚âî‚åàÔº´Ôº≠Œ∏
```
Find the largest adjacent pile.
```
A¬ª
```
Eat the current pile.
```
‚âîŒ£Ôº•Ôº´Ôº°‚åïŒ±ŒπŒ∏
```
Convert the piles back to integers and take the sum.
```
‚éöÔº©Œ∏
```
Clear the canvas and output the result.
[Answer]
# [Haskell](https://www.haskell.org/), 163 bytes
```
o f=foldl1 f.concat
r=[0..3]
q n=take(min(n+2)3).drop(n-1)
0#m=m
v#m=[o max$q y$q x<$>n|y<-r,x<-r,m!!y!!x==v]!!0#n where n=map(z<$>)m;z w|w==v=0|0<1=w
f=o(+).(16#)
```
[Try it online!](https://tio.run/##jVNNb5tAEL3zK4baB5AN2mEBO4rXl17bU48OB5SAHMWAAzTYkf@7O/vBFjepFKNZrWdn3nszs7vPu5ficLheGyhF2RyeDghl@NjUj3nvtGLHwpBnzivUos9fCq96rr16EfncD5/a5ujVAfoOm1Wict5o3TVQ5af5K5zJTpv5tr6cN0G7PMmlct2z656EeMtcl81qGPZFWxBylR@9dwr2q/t3GC4DRQh2YRsUg1OKxlv4oYfpzL/2Rdd3IGDngPnt6IuXAJwsIsNsSZ6EdinZimwtPUhniGSMPHfKQxlImUixmGZAviAAdgO8loAyQYaqJDTAOmmESQz5SnmYliMpIf4cGE0CVyGfKlakzKiO/q8Yp8AqITFhOMIoGrT6uNEvBagalBRZazwF5jeKudamiktUUqqTVGe5Ak5Mq3CsSsqQxChjI6s4@tDkUeTflqLhS@z0mMVZ6pmP6KRnlBz/i6y7Z2cem9LZOD7V77E9ll3dqEixG@Tkts18wq5nk5pr8PWJGuTV@kbzh6nbuxKPfdaIphLNxU1v0qlmZNEXoVcWOjVA8RTakklojawvR@Y4TpU/1/Qi6Qn/hOPv/lff/qhhLv@D9yDf6/e8KyDYQrdvBrCOxQK@EdSWVtqqM6@0x76vtt31Dw "Haskell ‚Äì Try It Online")
The `f` function takes the input as a list of 4 lists of 4 integers.
### Slightly ungolfed
```
-- helper to fold over the matrix
o f = foldl1 f . concat
-- range of indices
r = [0 .. 3]
-- slice a list (take the neighborhood of a given coordinate)
-- first we drop everything before the neighborhood and then take the neighborhood itself
q n = take (min (n + 2) 3) . drop (n - 1)
-- a step function
0 # m = m -- if the max value of the previous step is zero, return the map
v # m = 
    -- abuse list comprehension to find the current value in the map
    -- convert the found value to its neighborhood,
    -- then calculate the max cell value in it
    -- and finally take the head of the resulting list
    [ o max (q y (q x<$>n)) | y <- r, x <- r, m!!y!!x == v] !! 0 
       # n -- recurse with our new current value and new map
    where 
        -- a new map with the zero put in place of the value the mouse currently sits on 
        n = map (zero <$>) m
        -- this function returns zero if its argument is equal to v
        -- and original argument value otherwise
        zero w 
            | w == v = 0
            | otherwise = w
-- THE function. first apply the step function to incoming map,
-- then compute sum of its cells
f = o (+) . (16 #)
```
[Answer]
# JavaScript (ES7), 97 bytes
Takes input as a flattened array.
```
f=(a,s=p=136,m,d)=>a.map((v,n)=>v<m|(n%4-p%4)**2+(n-p)**2/9>d||(q=n,m=v))|m?f(a,s-m,a[p=q]=0,4):s
```
[Try it online!](https://tio.run/##jZLJbsJADEDv/QpfEBmYQGbJ1nboqV@BOERAuogskCrikH@nzsQDaatWPVjJjOznFzvvWZs129Nb/eGX1W5/ueTGy3hjaiNUxAu@Y2aVLYqs9ryWl3hoH4vOKyfaryeazWZy7pV@3b8s09Wu67yjKXlhWsa64invUX7Bs3VtjhsTcM3um8vD@g5gDaA5gMKQGAIjxIgwYoyEg8B7gfciwHOKT8wVWCMwT0Sw4bBcQjCgEkKklCIIZVOpNKRWMSHV0AL0V5SgtN5M/7SyLQIyk79YCYuyaeHIKCWsIAtFhpJaSGqhRyg1WKmRuDNKRgYhmQkq10MbYbHOSt6G5VTccJwS6Vh1pzTiQei09JXlJuGGbz/J1cejT6Zedqp9D8cKaVxq1EfS4sL/boJYcTJ4fdvSdauaHByD1mN/hogcnZcI5N8wt8OIivUNdoUjDAaYutss8ur0nG1fvTOYFWyrsqkO@8WhesGLOUz7yynMc@/MGLt8Ag "JavaScript (Node.js) ‚Äì Try It Online")
### Commented
```
f = (                    // f= recursive function taking:
  a,                     // - a[] = flattened input array
  s =                    // - s = sum of cheese piles, initialized to 1 + 2 + .. + 16 = 136
      p = 136,           // - p = position of the mouse, initially outside the board
  m,                     // - m = maximum pile, initially undefined
  d                      // - d = distance threshold, initially undefined
) =>                     // 
  a.map((v, n) =>        // for each pile v at position n in a[]:
    v < m |              //   unless this pile is not better than the current maximum
    (n % 4 - p % 4) ** 2 //   or (n % 4 - p % 4)¬≤
    + (n - p) ** 2 / 9   //      + (n - p)¬≤ / 9
    > d ||               //   is greater than the distance threshold:
    (q = n, m = v)       //     update m to v and q to n
  )                      // end of map()
  | m ?                  // if we've found a new pile to eat:
    f(                   //   do a recursive call:
      a,                 //     pass a[] unchanged
      s - m,             //     update s by subtracting the pile we've just eaten
      a[p = q] = 0,      //     clear a[q], update p to q and set m = 0
      4                  //     use d = 4 for all next iterations
    )                    //   end of recursive call
  :                      // else:
    s                    //   stop recursion and return s
```
[Answer]
# [Julia](https://julialang.org), ~~133~~ 127 bytes
```
*(A,S=136,I=keys(A))=((v,r,c)=maximum(i->(get(A,i,0),i[1],i[2]),I);S-=v;v>0 ? (A[r,c]=0;A*S*[(r+i,c+j) for i=-1:1,j=-1:1]) : S)
```
`-6` bytes by @MarcMush, thx!
[Attempt This Online!](https://ato.pxeger.com/run?1=jVK7TsMwFJUY8xVHwGAXt7LjJE2xXNSxCwyFKcpQQYtSaEGlrWDiQ1i68FHwNdxrA0LiIRY79j1PK0_Ps_V1M96-7uiL8WoMjypBlcEihXHIUaCL0sHQ0cBo9OjbwmQwOUxRw_ehiVHCoEfXjmEFeBaBOQl1HTMti2SfDEMDi-yLR49R7JJ-9zDM0OGCrg2DCRGULbulIL8UJbIPhiWGJWFi5Y4sytDBOtbosQ1nJTThkUaPNBRh5ffwhvl5bK8D0LEBs_JoksXuHDo8TcZhdGjfDQmjUsbPGSl5qBLrsR6pUqLfXiJQumVSJ8keCVlap2KgRt7YQg391eThTgyk9EJs1FKdSz8f3zfz9VyIy8mKgI3SUjWVqWlJa4npzRKNH0pHQqO237hNX-MIYlARu_baBXVVieVBo84PZh-Mtjk0aha2WkocYiSf16tpu3x5bP0rT9Pu_xxJUZgfkwxao9bfOb7GKHguhsfq5OxUev6XE-B22SxW1wuxuy9aNKPgnU4H-4IxuzKZLC4ie7uN-xs)
readable version:
```
*(A,S=136,I=keys(A))=(
(v,r,c)=maximum(i->(get(A,i,0),i[1],i[2]),I);S-=v;
v>0 ? (A[r,c]=0;A*S*[(r+i,c+j) for i=-1:1,j=-1:1]) : S)
```
* input: matrix (not a list of lists)
* works for arbitrary shaped matrices with positive numbers in it - as long as the path taken by the mouse is uniquely determined by the numbers.
* interesting math questions:
	+ what is the expected outcome of this "game"? (i got a value (approx.) between 18.2 and 18.3 with simulation
	+ what is the expected length of the path?
[Answer]
# Java 10, ~~272~~ ~~248~~ ~~239~~ 237 bytes
```
m->{int r=0,c=0,R,C,M=16,x,y,X=0,Y=0;for(;M-->0;)if(m[M/4][M%4]>15)m[r=M/4][c=M%4]=0;for(;M!=0;m[r=X][c=Y]=0)for(M=0,C=9;C-->0;)try{if((R=m[x=r+C/3-1][y=c+C%3-1])>M){M=R;X=x;Y=y;}}finally{continue;}for(var Z:m)for(int z:Z)M+=z;return M;}
```
The cells are checked the same as in [my answer for the *All the single eights* challenge](https://codegolf.stackexchange.com/a/175766/52210).  
-24 bytes thanks to *@OlivierGr√©goire*.  
-11 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##pZJBb6MwEIXv@RXeQyVQhhQHQ5JaziVnekgvSREHlpIVXXAqQrKhiN@enTG0UrXSatEeQGaMv/fmjV@TS@K8vvy8pUVyOrEwyXU7YSzXdVYdkjRjj/RpCiy18B3FUcxKW2K1m@DrVCd1nrJHppm6lc66pT8r5UKKzxY2ECoewBUa2GFhr1x5OFaWDB1n7Uo7P1hlFN6LOArvRLzmvl1GlTKFVFHp8/9vuKK9He3ssW5TPUTmRq3kpsfVVdMi0tqqMrqqarq59xweR41Kp5s7Wtrr0G5DtZU7dZV71ciuO@Q6KYqmTY@6zvU5kx2BL0nFnh9KI0IdvT882@FUvcsqq8@VZqHsbpL6fzt/L7D/IYbLMX9hJYZoPdVVrn9gVondJ/jUnOqsnB3P9ewNt@pCW3qWWjr7xYZY21aAB3PgHbQ@BLCAJa44FjhwF1b04QEXwH3gQdfZZgr/Rl4ChxWeJQZHtiH0PB8lF7R2UR3VxDgyx@MeiC@eV@SXXM//xzMxfHOWGyZyeqMe2Z8DNTCHJYjRZA99It1HQIAAitgjsE8ZcdMMySIX5mNzJp8f0XLS8Ychuj0OcMoG7o@eIAXaXwNBCbj9DBcmmEFS0P0ZSR4GZLyhRUzhL/McRf56D9Ca6INGKjVAIh6lEoz2/Ad50ZMDwokPtFH5JHeT7vYb)
**Explanation:**
```
m->{                       // Method with integer-matrix parameter and integer return
  int r=0,                 //  Row-coordinate for the largest number, starting at 0
      c=0,                 //  Column-coordinate for the largest number, starting at 0
      R,C,                 //  Row and column indices (later reused as temp integers)
      M=16,                //  Largest number the mouse just ate, starting at 16
      x,y,X=0,Y=0;         //  Temp integers
  for(;M-->0;)             //  Loop `M` in the range (16, 0]:
    if(m[M/4][M%4]>15)     //   If the current cell is 16:
      m[r=M/4][c=M%4]      //    Set `r,c` to this coordinate
        =0;                //    And empty this cell
                           //  (after this first loop, `M` will be -1)
  for(;M!=0;               //  Loop as long as the largest number `M` isn't 0:
      ;                    //    After every iteration:
       m[r=X][c=Y]         //     Change the `r,c` coordinates,
         =0)               //     And empty this cell
    for(M=0,               //   Reset `M` to 0
        C=9;C-->0;)        //   Inner loop `C` in the range (9, 0]:
          try{if((R=       //    Set `R` to:
            m[x=r+C/3-1]   //     If `C` is 0, 1, or 2: Look at the previous row
                           //     Else-if `C` is 6, 7, or 8: Look at the next row
                           //     Else (`C` is 3, 4, or 5): Look at the current row
             [y=c+C%3-1])  //     If `C` is 0, 3, or 6: Look at the previous column
                           //     Else-if `C` is 2, 5, or 8: Look at the next column
                           //     Else (`C` is 1, 4, or 7): Look at the current column
               >M){        //    And if the number in this cell is larger than `M`
                 M=R;      //     Change `M` to this number
                 X=x;Y=y;} //     And change the `X,Y` coordinate to this cell
          }finally{continue;}
                           //    Catch and ignore ArrayIndexOutOfBoundsExceptions
                           //    (try-finally saves bytes in comparison to if-checks)
  for(var Z:m)             //  Then loop over all rows of the matrix:
    for(int z:Z)           //   Inner loop over all columns of the matrix:
      M+=z;                //    And sum them all together in `M` (which was 0)
  return M;}               //  Then return this sum as result
```
[Answer]
# SAS, ~~236~~ 219 bytes
Input on punch cards, one line per grid (space-separated), output printed to the log.
This challenge is slightly complicated by some limitations of arrays in SAS:
* There is no way to return the row and column indexes of a matching element from multidimensional data-step array - you have to treat the array as 1-d and then work them out for yourself.
* If you go out of bounds, SAS throws an error and halts processing rather than returning null / zero.
## Updates:
* Removed `infile cards;` statement (-13)
* Used wildcard `a:` for array definition rather than `a1-a16` (-4)
## Golfed:
```
data;input a1-a16;array a[4,4]a:;p=16;t=136;do while(p);m=whichn(p,of a:);t=t-p;j=mod(m-1,4)+1;i=ceil(m/4);a[i,j]=0;p=0;do k=max(1,i-1)to min(i+1,4);do l=max(1,j-1)to min(j+1,4);p=max(p,a[k,l]);end;end;end;put t;cards;
    <insert punch cards here>
    ; 
```
## Ungolfed:
```
data;                /*Produce a dataset using automatic naming*/
input a1-a16;        /*Read 16 variables*/
array a[4,4] a:;     /*Assign to a 4x4 array*/
p=16;                /*Initial pile to look for*/
t=136;               /*Total cheese to decrement*/
do while(p);         /*Stop if there are no piles available with size > 0*/
  m=whichn(p,of a:); /*Find array element containing current pile size*/
  t=t-p;             /*Decrement total cheese*/
  j=mod(m-1,4)+1;    /*Get column number*/
  i=ceil(m/4);       /*Get row number*/
  a[i,j]=0;          /*Eat the current pile*/
                     /*Find the size of the largest adjacent pile*/
  p=0;
  do k=max(1,i-1)to min(i+1,4);
    do l=max(1,j-1)to min(j+1,4);
      p=max(p,a[k,l]);
    end;
  end;
end;
put t;              /*Print total remaining cheese to log*/
                    /*Start of punch card input*/
cards; 
  4  3  2  1  5  6  7  8 12 11 10  9 13 14 15 16 
  8  1  9 14 11  6  5 16 13 15  2  7 10  3 12  4 
  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 
 10 15 14 11  9  3  1  7 13  5 12  6  2  8  4 16 
  3  7 10  5  6  8 12 13 15  9 11  4 14  1 16  2 
  8  9  3  6 13 11  7 15 12 10 16  2  4 14  1  5 
  8 11 12  9 14  5 10 16  7  3  1  6 13  4  2 15 
 13 14  1  2 16 15  3  4  5  6  7  8  9 10 11 12 
  9 10 11 12  1  2  4 13  7  8  5 14  3 16  6 15 
  9 10 11 12  1  2  7 13  6 16  4 14  3  8  5 15 
;                    /*End of punch card input*/
                     /*Implicit run;*/
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~42~~ 41 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
16{√ó‚ç∫:a‚àá‚ç®+/,m√ó‚åà/‚åà/‚ä¢‚å∫3 3‚ä¢a‚Üê‚çµ√ó~m‚Üê‚ç∫=‚çµ‚ãÑ+/,‚çµ}‚ä¢
```
[Try it online!](https://tio.run/##hVFLTgJBEN1zitrNTJTQNd09gyYeZhKDIUIwhI0hujKICkYXhrWuvIAbttykL4KvqhvFGOOCSXfX@9R7NBeD9ullMxidbcPjS38UZk9m28OXq@lmFZbr4ybMb8Py/aBzOMTDYt7R3/1bWKwtWRwaoMPyY7O6HuppfYJbeLgBA4crILbbCSZTeb57HePYE@FsdJ4BlvWa/iDDA8bjq1YeZs85OSJLVBJxkZMnqohqom6Rc0nMxIboCBdL7Ig9cVUUEzKJ3AUNc8wAYSUrRPFeZWtcjHhAj9w@mXVu5fWnswgaNS9/OXMky9zrgBUvMhzNrO4AZawhBtjRJbJNzlacZCsPSCUQCWtB9pqGdSeoQ5MxL9W5/A4dDVNOVjUfGzOJIMVGAZiItftia7DYqtNdjVYm4WOKqCv/TCm6YPtdbLsTlWYq7fifAsGuu8l7v9dUv9PcytNdRMpqhip5syn/pteRXinD7ehJK9Ftq/0J "APL (Dyalog Unicode) ‚Äì Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~31 30~~ 29 bytes
```
¬≥≈ìi‚±ÆZI·ªä»¶
‚Å¥·πñ≈íP≈í!‚Ç¨·∫é‚Å¥;‚±Æ·π¢√á∆á·π™
F·∏ü√áS
```
Since the method is far too slow to run within 60s with the mouse starting on `16` this starts her off at `9` and limits her ability such that she is only able to eat `9`s or less **[Try it online!](https://tio.run/##y0rNyan8///Q5qOTMx9tXBfl@XB314llXJYPd047Oing6CTFR01rHu7qs7QGSj7cuehw@7H2hztXcbk93DH/cHvw////o6MVLHUUDA2A2BCIjWK5dKIVgCwFIyC2AIoYg0XMgCwgVjAB0iZgEWMgzxyITYEiprGxAA "Jelly ‚Äì Try It Online")** (thus here she eats `9, 2, 7, 4, 8, 6, 3` leaving `97`).
### How?
```
¬≥≈ìi‚±ÆZI·ªä»¶ - Link 1, isSatisfactory?: list of integers, possiblePileChoice
¬≥        - (using a left argument of) program's 3rd command line argument (M)
   ‚±Æ     - map across (possiblePileChoice) with:
 ≈ìi      -   first multi-dimensional index of (the item) in (M)
    Z    - transpose the resulting list of [row, column] values
     I   - get the incremental differences
      ·ªä  - insignificant? (vectorises an abs(v) <= 1 test)
       »¶ - any and all? (0 if any 0s are present in the flattened result [or if it's empty])
‚Å¥·πñ≈íP≈í!‚Ç¨·∫é‚Å¥;‚±Æ·π¢√á∆á·π™ - Link 2, getChosenPileList: list of lists of integers, M
‚Å¥               - literal 16
 ·πñ              - pop -> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
  ≈íP            - power-set -> [[],[1],[2],...,[1,2],[1,3],...,[2,3,7],...,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]]
      ‚Ç¨         - for each:
    ≈í!          -   all permutations
       ·∫é        - tighten (to a single list of all these individual permutations)
        ‚Å¥       - (using a left argument of) literal 16
          ‚±Æ     - map across it with:
         ;      -   concatenate (put a 16 at the beginning of each one)
           ·π¢    - sort the resulting list of lists
             ∆á  - filter keep those for which this is truthy:
            √á   -   call last Link as a monad (i.e. isSatisfactory(possiblePileChoice)
              ·π™ - tail (get the right-most, i.e. the maximal satisfactory one)
F·∏ü√áS - Main Link: list of lists of integers, M
F    - flatten M
  √á  - call last Link (2) as a monad (i.e. get getChosenPileList(M))
 ·∏ü   - filter discard (the resulting values) from (the flattened M)
   S - sum
```
[Answer]
# J, 82 bytes
```
g=.](]*{:@[~:])]_1}~[:>./]{~((,-)1 5 6 7)+]i.{:
[:+/[:(g^:_)16,~[:,0,~0,0,0,.~0,.]
```
[Try it online!](https://tio.run/##hZFNTsMwEIX3PcUsWCQ0uBn/pbEUxD0i0wWiLWx6gKi5evDMxOCwADlSFvPeN8/Pn8tyGVSs4uMUXsY5xDqe8D6P4Vkd4jRXVfNUIzjw0NX7@KGmsDsPagz7wxiqy2s41eibJG/aZm4bOir9VVx272/XG6CGAc5g03kAAx1gC0w70ggNoIMeECEJMH2AHkCLty2sSZ@GJLWs9kRJWiGAhhVtCJscsK4vEcg6w2PHiI65PTkTdA1kiUgxBGEKBOlcjtAzC3mz4TiaoZqhtkBsSiBTroHkRRFlE7mK7xj2VxuyXhqQEJyAIoovY2iPMBxuGXJnKZXyi7XL92I2laU5nDC6Y9mHyTs0P4b7p97cR7sppBRgjm6ynfumd/WcyP1AzN8QeRbPRrtCViBBli8 "J ‚Äì Try It Online")
I plan to golf this more tomorrow, and perhaps write a more J-ish solution similar to this [one](https://codegolf.stackexchange.com/questions/175724/all-the-single-eights/175742#175742), but I figured I'd try the flattened approach since I hadn't done that before.
[Answer]
# [Red](http://www.red-lang.org), 277 bytes
```
func[a][k: 16 until[t:(index? find load form a k)- 1
p: do rejoin[t / 4 + 1"x"t % 4 + 1]a/(p/1)/(p/2): 0
m: 0 foreach d[-1 0x-1 1x-1 -1x0 1x0 -1x1 0x1 1][j: p + d
if all[j/1 > 0 j/1 < 5 j/2 > 0 j/2 < 5 m < t: a/(j/1)/(j/2)][m: t]]0 = k: m]s: 0
foreach n load form a[s: s + n]s]
```
[Try it online!](https://tio.run/##hVLbasJAEH3PVxyEglIkO7lpQy//0NdlH4JJaKImohH8ezszG4tVaQnZzezOnHPmTPZVef6sSuuCOse5PnYrWzi7zkEZjt3QbOyQT5uurE4fqHnHpi9K1P1@iwLr2RwU7HKUPfZV2zedHRAiwTNocpoMePLfrginu5BmskazHCbY8iIoVbH6QmnnBHPihWSZ08lAXv6Qcz52ts2xY6gyaGoUm41tQ8I7Y8j@ipT3aIwjjbe8DjmYuFViPp85y7SDcwZv4A637iBSLiq669YsXx2Yr3MHd97tm25ADctPAsRABNbEUQpkwAJYckQRiLUa4EWiGJSAUjbSwSG4BllyOWdxgiSSgvhELUuVYCGREToGRnIHQpoV69WNEoE2Kib6W4lkpXpLvkzwaOSOVRRziC7hYtnJo3ZiIRapqSRmkihexAKSap/kVTIRo/OfheiRJ57@4gIpajoaay5lMgKPI3R3INr0OIFEGzDeWPHGNzcSyCgjJbjxJL7gq3mZzuN/m2@U/JrAOKvEe6LlKk0hY@0se6DkIchiBMm0LPkBGSEF5PwN "Red ‚Äì Try It Online")
It's really long solution and I'm not happy with it, but I spent so much time fixing it to work in TIO (apparently there are many differences between the Win and Linux stable versions of Red), so I post it anyway...
## More readable:
```
f: func [ a ] [
    k: 16
    until [
        t: (index? find load form a n) - 1
        p: do rejoin [ t / 4 + 1 "x" t % 4 + 1 ]
        a/(p/1)/(p/2): 0
        m: 0
        foreach d [ -1 0x-1 1x-1 -1x0 1x0 -1x1 0x1 1 ] [
            j: p + d
            if all[ j/1 > 0
                    j/1 < 5
                    j/2 > 0
                    j/2 < 5 
                    m < t: a/(j/1)/(j/2)
            ] [ m: t ]
        ]
        0 = k: m
    ]
    s: 0
    foreach n load form a [ s: s + n ]
    s
]
```
[Answer]
Not my best work. There's some definite improvements to be done, some probably fundamental to the algorithm used -- I'm sure it can be improved by using only an `int[]`, but I couldn't figure out how to efficiently enumerate neighbors that way. I'd love to see a PowerShell solution that uses only a single dimensional array!
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 348 bytes
```
Function F($o){$t=120;$a=@{-1=,0*4;4=,0*4};0..3|%{$a[$_]=[int[]](-join$o[(3+18*$_)..(3+18*$_+13)]-split',')+,0};$m=16;while($m-gt0){0..3|%{$i=$_;0..3|%{if($a[$i][$_]-eq$m){$r=$i;$c=$_}}};$m=($a[$r-1][$c-1],$a[$r-1][$c],$a[$r-1][$c+1],$a[$r][$c+1],$a[$r][$c-1],$a[$r+1][$c-1],$a[$r+1][$c],$a[$r+1][$c+1]|Measure -Max).Maximum;$t-=$m;$a[$r][$c]=0}$t}
```
[Try it online!](https://tio.run/##jVRNj5swED2HX2FFrhY2gGy@kgoh9dK0l1WrqlIPCEWIeLtUBFJwtCsl/PZ0bGzyWWkPNvbw5r3nGcvb5pW13QurKqdoWnZc7uqCl02NfrKOf6sZMjGHlY3Z25YVnK0ttJ8YE5wXfJdXKEFLJAHGpHwGrAo7kHiegaYShJZ5WbG1i9Bn9e@EguCXhiPFMEUH9KstOXO@NpDXI1Z17MTzPe86tp6i3ugNY7T8Y1cL1x3aGxNtf5qiFAU2Qj4MDwbNbIiEsIpgzGEsRITCP0phEIh8lBHIoJBJAUujDGVTRK54F4JP4AVS5lDFO@RollBpz2WEDG6EIgru8lKF9yXirl@pSZRn7z9@6SWvxIcKRTWLVKGjO1@5F/ryBNKJOGkw8vpXfv3BmTxZKHOiIUdW1Ze8oaoT1WcSLoQuFVhv8OvdKbC2eConVXLh2Dgy0thDuzU52JGGg1vioXJjtwN1bqI7J2utazOKy7vkSXFBHF6X2D/THtoSqQvw/mYK4vniyvFNv8dbEugaD4TqHIOUrwoTjY4p8d7NPB@ZI8UTnDOPWprZN/rTA7I0cWPtMU@oR2KcJ5/2Dk1s8hjEgfz0MXFd//Bhj/MUr7IkLWueZpnp/GnKGjep6c/o4hGvLNfVyxn1rczptlXJH@wHa2aTPsabhEbx6ws8LCbeOL85sfaauEzwSquUz6YQKjMh5rC/eAPm2gSXMS4A1veSSmJahwKqgNk@215sZvrfzWbMmtE724sNzIcnlne7liHnKX@zXJjKzW4TY@4kGD6aNEtIj3l/1C/c8R8 "PowerShell Core ‚Äì Try It Online")
---
More readable version:
```
Function F($o){
    $t=120;
    $a=@{-1=,0*4;4=,0*4};
    0..3|%{$a[$_]=[int[]](-join$o[(3+18*$_)..(3+18*$_+13)]-split',')+,0};
    $m=16;
    while($m-gt0){
        0..3|%{$i=$_;0..3|%{if($a[$i][$_]-eq$m){$r=$i;$c=$_}}};
        $m=($a[$r-1][$c-1],$a[$r-1][$c],$a[$r-1][$c+1],$a[$r][$c+1],$a[$r][$c-1],$a[$r+1][$c-1],$a[$r+1][$c],$a[$r+1][$c+1]|Measure -Max).Maximum;
        $t-=$m;
        $a[$r][$c]=0
    }
    $t
}
```
[Answer]
# C (gcc), 250 bytes
```
x;y;i;b;R;C;
g(int a[][4],int X,int Y){b=a[Y][X]=0;for(x=-1;x&lt2++x)for(y=-1;y<2;++y)if(!(x+X&~3||y+Y&~3||a[y+Y][x+X]<b))b=a[C=Y+y][R=X+x];for(i=x=0;i<16;++i)x+=a[0][i];return b?g(a,R,C):x;}
s(int*a){for(i=0;i<16;++i)if(a[i]==16)return g(a,i%4,i/4);}
```
[Try it online!](https://tio.run/##XZLBbuIwEIbPy1NMK7HEjavGOKRsjdVD34ATyPUhhICMdqEi6SpZyr46HY9TipAITmb@7/eMPcX9uihOp0a1yqmFmqoX1VtHbltDbqxJLfevM/qfs8NC52ZuzczqRK12@6jR90I1k6GK44b5QOsDLQVa5lbRTdTEs5//5cdHG89pzQ2@WYNhO1kw5h1f9DxurZnqWdxY8nW6wR3cRGRo5FgToyqxxlm1L@v3/RYWz@so51P@wp4adexVvuK7nB0CfIFiDTlyWouMdawnXT/l7iFl6njyrdVlVVcms0ZkFjQcej8OgsOQg@SQchhxyDg8chhz@MVBJPhgXqBAoEKgRKBGZEd@RY4Jy8jimsw6ytOSSFSLoEuDLoCklEE9JEPvI4NNGvZMLsyChySzx4COgjgjgzGV1lUrz4ahy/FFX13RIuhTMvTFDIm87udcnCQjL@wwSba@htGxd1Q9f@Rl81YWdbk04cSRTujXtSUS2Qn/5G4b/d25JfP3ghcMNJ4bpBKFywQq96/crSK6RPbQfd2FTwVxvCHyG3UBdYjilIAfE3jbY2YV3faHy35xy7uJ2PiZ44DTorWEZxi8bgfwBAMYMIWO3mxfVu@/a3Ssoi@Gcl@GXb6/hH6hcXndonsI8jOsv49jY/0@mra5GfDLhPfF8zt9Ag "C (gcc) ‚Äì Try It Online")
Note: This submission modifies the input array.
`s()` is the function to call with an argument of a mutable `int[16]` (which is the same in-memory as an `int[4][4]`, which is what `g()` interprets it as).
`s()` finds the location of the `16` in the array, then passes this information to `g`, which is a recursive function that takes a location, sets the number at that location to 0, and then:
* If there is a positive number adjacent to it, recurse with the location of the largest adjacent number
* Else, return the sum of the numbers in the array.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 149 bytes
```
(g@p_:=#&@@Position[s,Max@p];m=g[s=#];While[Tr[b=s[[##]]&@@#&/@Select[#+m&/@Tuples[{-1,0,1},2],Max@#<5&&Min@#>0&]]>0,m=g@b;s[[##&@@m]]=0];Tr[Tr/@s])&
```
[Try it online!](https://tio.run/##jZHRasIwFIbv9xSBQNlYho1tWl1XyQsIwoRdhDCqVC1YFdvBoPTZu5OTRAURdhHanJzz/X/@1EW7K@uirdbFsMmH5608fb/nNJBycWyqtjoeVMPmxa886azOt6rJqc6@dtW@VMuzWuWNUpRqDf00GMnPcl@uW0Vfa9gsf077slHdG2ch4z0bawTRDxEE8@og6SwMtJ6FDLhylSEJOLXWeagzoC/PI9nol2BYnKtDS0aSbGA9dV0XMxIxMmYEsKQTjCSMpIxMzI6bMocVMjLFArRymODQx5MeSoCYwD@cmxPs4ciwHX5GoESK@xAVDTt2BI6nkSnceZhaebQxfugBW4Q74G4uQmOpHxJWFE3BF2zHN4QIJQ1HmIYEGzCACAHCXpE7kyhkxsH6NQcrer02t1BxCTP0I1CInV2j2DMXJLeiU68h/JAppP5OF4XYPp3wMUQXps0qsbH8J1pLuI8bFWKfQ4q5CP/Ykb1P4jw8BqQekNiJ@IbggADoh@EP "Wolfram Language (Mathematica) ‚Äì Try It Online")
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 281 bytes
```
D,f,@@,VBFB]G‚Ç¨=dbLRz‚Ç¨¬¶*bMd1_4/i1+$4%B]4 4b[$z‚Ç¨¬¶o
D,g,@@,c2112011022200200BD1‚Ç¨Œ©_2$TAVb]8*z‚Ç¨k√æbNG‚Ç¨lbM
D,k,@~,z‚Ç¨¬¶+d4‚Ç¨>¬¶+$d1‚Ç¨<¬¶+$@+!*
D,l,@@#,bUV1_$:G1_$:
D,h,@@,{l}A$bUV1_$:$VbU","jG$t0‚Ç¨obU0j","$t‚Ç¨iA$bUpVdbLRG‚Ç¨=‚Ç¨!z‚Ç¨¬¶*$b]4*$z‚Ç¨¬¶o
y:?
m:16
t:120
Wm,`x,$f>y>m,`m,$g>x>y,`y,$h>x>y,`t,-m
Ot
```
[Try it online!](https://tio.run/##PY/PTsMwDMbvfQpvhEtrRJxlY1RQumpiFwYSYuVQVRuh2v9qO/SwguDAwyAh8Qwc4M5D8CLFYRNSEv8c@7P13WXZel1VXRxjGGIcnUdp7@fl/TQzF9cPDJ@vrulnNNSHM/KE3o9SDdokYltbOV2cWOG9IlKSSCqlpOQTdYk7vt@GStx0YpO2XatYfH2YSzt/afosXWD4jNtJXqY5Bgwis8oTS6FXc7ltyRv20AxiGgq/Zx/@nNq1j8unjtgVRGwGdazPe6KQPGBlBnLOuSg4mdmudWxN/bnjW9u5EybV7r@d0j9zcp9aTuGzH@c2x9EGxTgoA6YcxSTYBCWOShTTLRV4kDtXRVVVSdKAIyAJzRSSFrSBFFCDmZpwDESgLWsgoBaoNP0F "Add++ ‚Äì Try It Online")
Oof, this is a complicated one.
**[Verify all test cases](https://tio.run/##fVDNbtNAEL77KaZhe0k2Yme9dn5ETRpF5EJAqog5RFbK4v6kTZpIdaUEBAceBgmJZ@ihvfMQPAhmZtdGikBI@Zmd@X7mm3d5vtmU5Uiey8FApsMXw2z888v3o9y@PPlAxcPXpp3kODdPF9gS5nCYGTB2JvxsHYzkBRPfa0StEJXWWin6DEdIiB/f5lq8OU5t1m0y4/rx3r5i/aWdEPVaDj5Lr9TKDf0nVIicmc@4GrQOmgRbksMTaacpzkV/zD/UvGTbj8tPx6IaiNROG7JxNRaFIoG1naoreouCHgtGbVIO5dLR96BKJ2xmmn/i7PrPg1Uf46DoU57g7UqebqU4T3YJVSspLpJtspOnOykufVXI9ip4XZRlOZsZCEEDZjCLIIYOdKlCaiCggh4/QkADGAHGWUaELiD0qMUjJIobeFhESh2uFYmSiHEEpG4IZs@hx@rsof/hwKPItdBBaexlQzbTwHYaumBqQkiqRIqoH1Of1w8ZH/Gi6KxZjeCgqwysWq@NTI@q3MqjgA7jOFEdmpf1BzG8hvKxO267SsnwJT2hyuSUSJBW@c8JmLB/ERIyPgSB2Y65Ia8W1w5/ETqeEDPK1AxHJsKv9aZYrG9uy3b79m5RnP0G)**
## How it works
For this explanation, we will use the input
\$M = \left[\begin{matrix}
3 & 7 & 10 & 5 \\
6 & 8 & 12 & 13 \\
15 & 9 & 11 & 4 \\
14 & 1 & 16 & 2 \\
\end{matrix}\right]\$
We start by defining a series of helper functions. We will use \$x\$ to represent an integer such that \$1 \le x \le 16\$, \$M\$ to, initially, represent the \$4\text{x}4\$ input matrix. The functions are:
* \$f(x, M)\$: Given a value and a \$4\text{x}4\$ matrix, return the co-ordinates of \$x\$ in \$M\$ e.g. if \$x = 16\$ and \$M\$ is above, \$f(x, M) = (4, 3)\$
* \$g(M, y)\$: Given a matrix and two co-ordinates, return the largest of the neighbours of the value at that point e.g. using \$f(x, M)\$ from above, \$g(M, f(x, M)) = 11\$
This implements the two helper functions:
\$k(x)\$ which removes any co-ordinates which would wrap around or be out of bounds
\$l(M, y)\$ which, given a matrix and co-ordinates, returns the value at those co-ordinates
* \$h(y, M)\$ which, given a matrix and co-ordinates, sets the value at those indexes to \$0\$
After these functions are defined, we come to the main body of the program. The first step is to assign the four variables, **x**, **y**, **m** and **t**. **x** is set to \$0\$ by default, **y** to the input, **m** to \$16\$ (the first value to search for) and **t** to \$120 \: (1 + 2 + \cdots + 14 + 15)\$.
Next, we enter a while loop, that loops while **m** does not equal \$0\$. The steps in the loop go something along the lines of
While **m** \$\neq 0\$:
* Set **x** to \$f(\textbf{y}, \textbf{m})\$. For the first iteration, this sets **x** to the co-ordinates of \$16\$ is \$M\$ (\$x := (4, 3)\$ in our example)
* Set **m** to \$g(\textbf{x}, \textbf{y})\$. This yields the largest new neighbour to **m**, or \$0\$, if there are no new neighbours (which ends the while loop).
* Set **y** to \$h(\textbf{x}, \textbf{y})\$. This sets the previous value of **m** (\$16\$ in the first iteration) to \$0\$, in order for the previous step to work
* Set **t** to \$\textbf{t} - \textbf{m}\$, removing that value from the total value amount.
Finally, output **t**, i.e. the remaining, non collected values.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 258 bytes
Without LINQ. The using System.Collections.Generic is for the formatting after - the function doesn't require it.
```
e=>{int a=0,b=0,x=0,y=0,j=0,k;foreach(int p in e){if(p>15){a=x=j/4;b=y=j%4;}j++;}e[x,y]=0;while(1>0){for(j=-1;j<2;j++)for(k=-1;k<2;k++){try{if(e[a+k,b+j]>e[x,y]){x=a+k;y=b+j;}}catch{}}if(e[x,y]<1)break;e[x,y]=0;a=x;b=y;}a=0;foreach(int p in e)a+=p;return a;}
```
[Try it online!](https://tio.run/##pZRNj5swEIbv/Iq5VAJlNsF8JZFjLpXay1aq1MMeoqgixLsxsBAB6QYh//Z0nFTbjUK6WhU0Qp4vP35tkzZ3aVXL475R5RP86JpWPo8/V0Uh01ZVZTP@KktZq5RbbzO4lRZJ08D3unqqk@feAtjt14VKoWmTlj6/KrWBb4kqbccEAb7sy3ShynaJK6RPDBsQRyningaQCBfXZAeyjiwjy/kjcSXp1jYZO1AlSKdXj/YuZqHTJ@IgsknA16IT2aeA62w04louD9ithMtftqqQNotdp6c2dibuGM8WHqcsxzhy48jJkZOjb@vOdJbLZJTjepSt4nMjpz8IcvFOkJNrnSZtuu21PuWahAVz1gSZ89eJicswcU1rGlpBMhI7Xst2X5eQcH3k1r1q2j/KxPCzoBEIKOULXAR6y7jOox4mE/ek6tunhwB99JBpvI6FGOEUZ0MhRiUMmYvzwaiPLEAWIov0RZSSL4kYDFQTj4/BB4nmhsYwef9J5F1X@zQpdQ@HOkc4Q6OGPzhtiHMDNbgYA0Q86L1DFLLr2tl5qTfkDzA8qRENRackLsPohkqBOQzhexq53oc3AMFDOmwwLBRtKjEDGxTKp0BEOz/AdQXmDxzxOdW7ZMTwL7jpLbjoNP8J/hbfDMHgh/qv29KaW28uMyGe7/PpujrW62@zbKpCjh9q1cp7VUp7Y@8ch1ua3uNv "C# (.NET Core) ‚Äì Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~151~~ ~~136~~ ~~126~~ ~~125~~ 119 bytes
```
{my@k=$_;my $a=.grep(16,:k)[0];while @k[$a] {@k[$a]=0;$a=^@k .grep({2>$a+>2-$_+>2&$a%4-$_%4>-2}).max({@k[$_]})};[+] @k}
```
Super shabby solution. Takes input as flattened array.
[Try it online!](https://tio.run/##RY3BjoIwFEX3fsVdVCNxNLy21MFKw38QJF2gTpDEOAslhG/HVzSaNO1res7ptb5dzNh2WByzsW@7vMlEZfkufLY53errkszPromKuLT389@lRt4UwpfoX2cWWyYPeYMX3Usn/MrJtah4Xwg/1zzOtVvLIdq0/rGcxKocosEWq5Jzw2hn/77DEXuFLShGAoNfkAQpUIIURNAgXiAD6T68hgJTk7B9KxQK6aTqYJP58ml4C0SQZPhMscnNqa64wHzi7PgE "Perl 6 ‚Äì Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum -p`, 137 bytes
```
splice@F,$_,0,0for 12,8,4;map{$k{++$,}=$_;$n=$,if$_&16}@F;map{map{$n=$_+$"if$k{$"+$_}>$k{$n}&&!/2|3/}-6..6;$k{$"=$n}=0}@F;$_=sum values%k
```
[Try it online!](https://tio.run/##HY7LDoIwEEV/ZTQjGwp2QOqD1LhypUvXDTGYNCA0Ft1gf91aSGZxc87cyZj61RbeW9Pqe306M1SMM/7oX0AZ27FN@azMiM0Yx8icRFViJ5HpB6qIhDudZz/vBK5iXAbVjLiMUbnjlDoXRYt19s3XLhFpKspZy8Aln/qopH0/4VO179quGu9z2AJxKEDALjwBlAMVsAci2ACFARKQwa83g@4765PrRdvhcLgNup1OBVCknLhPTPUH "Perl 5 ‚Äì Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 49 bytes
```
{{h[,x]:0;*>(+x+0,'1-!3 3)#h}\*>h::(+!4 4)!x;+/h}
```
[Try it online!](https://tio.run/##bZDdasMwDEbv9xQqG6xpWhZFdv4EfZEu0N1kGR0dlF6khO7VM39yMzYo@MbW0dEnHzbH9@M0dc049rv10DaZrrbLdEiz9TNvFkKSPPbX19W2b5plunDkksWg6Ut/nc7N@LS7fJ@ajgbdfx10ue/ePj510Iuekvb6cN45EsqJyVNBJVXE4cLEGdXEQuyIPXGhGVEb6FBHwYEpCBWjfFCUaBL0u5nm8Czkft01ENjzf26@0ZndzV3DBKVgSB7689DvQEukJQ6EupqFHhMYWDjIlmuoxNwwxrDmNSsmwnxr8Cpu3tJC2qb@hpUWyRQOP@bVc8wdV8FbAfH9jbWsjP77B3G0GGmbCxSQKGf5Hdo@pADkIm59oKWdfgA "K (ngn/k) ‚Äì Try It Online")
the input (`x`) is a 1d array
`(+!4 4)!x` a dictionary that maps pairs of coords to the values of `x`
`h::` assign to a global variable `h`
`*>` the key corresponding to the max value
`{` `}\` repeat until convergence, collecting intermediate values in a list
`h[,x]:0` zero out the current position
`+x+0,'1-!3 3` neighbour positions
`(` `)#h` filter them from `h` as a smaller dictionary
`*>` which neighbour has the max value? it becomes the current position for the new iteration
`+/h` finally, return the sum of `h`'s remaining values
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~124~~ 115 bytes
```
(p=#&@@Position[m=Join@@ArrayPad[#,1],16];Do[m[[p]]=0;p=MaximalBy[#&@@p+{0,-1,1,-5,5,-6,6,-7,7},m[[#]]&],16];Tr@m)&
```
[Try it online!](https://tio.run/##jVNNi9swEL37V6gxhC6VQWNZcsqiopZSaGEhh96EDqLdUMM6CbEPXYJ/eyqNPpLSlu5hsBm9ee/pjT26@cfj6Obhm7vs1OX1UdVrrbeHaZiHw96M6sth2Gv9/nRyz1v33dQULAVp7z8ezGjM0VrF7o/qwf0cRvf04dmE8eObM6MNUKCNoII2kkra9LRfqB@prV1Hiq8nPd6tL/PjNE9EkfOZnElHCeG@Wl@wUN8R/k366n1tQgf8GYAv5jtvseMnwE@Cx4JcyEKad4TRKhBuAlEABgiCIRFGcB4XSbTHDos2ghTpfieEBOR49FeHKMaSy/afDgEJESjSMeRxpIfihye/QRg9o4Vwt@6GkEeHPHrBSwgEywjG5DgSihQJ5FsE@SAIAdtmh@01xGzqGhkkHVG2wso8jbvMrN5HstgVxphO2WGXrsjyWjDPHENRxS@kRdXIKFKM/EYtZi7TWl@@qcjYb6LHP7ZYdt/lHCNTch41eMpA3ngE1v6Psi@UMhF0t5RF5ErJq6WqtqdhP5vPO7PTNVFKkdqTrbZumlb@@ckNT69Wltg10VoT/NOqncGnMf4HtdZefgE "Wolfram Language (Mathematica) ‚Äì Try It Online")
This takes a 2D array, pads it on each side, then immediately flattens it so we don't have to spend bytes indexing. The only cost to this is `Join@@` to flatten. Afterwards it proceeds as below.
**124-byte version** for a 2D array: [Try it online!](https://tio.run/##jZNPa9tAEMXv/hRbC0RL1nhHK8kORkEpbSGHgA@@CR2WxCYCyxbSBhKM/dXd2dk/dkhLe1hsZmd@7@0bu1X6Zd0q3Typ86Y4f@2KKC7L5X5odLPfVW0Rne77Xr0v1fMJOOT14sceq4@qu9eViHnLu3phhx7VW9Oq7ff3qruJ4mm5eu2266E6CD7BySNPat6efr7pXj3pUxTXRFv11aqflm39LT7r9aAHVrDDgR1YyhmTeBI8OIyVDL/leGZ45qYCeAeAR2Dllio4ATgJ2Av5kR3Z5I4JPjLAuQGZRtNCzeCAttmPZ050RhVhbRgpln4EgmuUdPVHhyQmnMvkrw6BgNSYuWvw44SH4Ec6v0aYPJMF87b0CiitQ2m90CMyas5tMyUnCZi5SMC/wsgbQTC9iXeYXEL0pi6RgdPJwlZEmOd2l56KPpzFNBBtOmGHqXui8GuhPH0MQZV@IQmpWmLmYpRXajbz3K31/zdlibO59fhpi2H3qc/RkpxzqyFdBvmVRxDJv5CzgMwdIL1GBpELUo6Oo9Gyb3a6ethUmzJiRVGwCGHjpRqGMX7@Us32y7hmdczKsmT0Tzv/Bg "Wolfram Language (Mathematica) ‚Äì Try It Online")
Mostly my own work, with a bit derived from [J42161217's 149-byte answer](https://codegolf.stackexchange.com/a/176612/39328).
Ungolfed:
```
(p = #& @@ Position[m = #~ArrayPad~1,16];     m = input padded with a layer of 0s
                                              p = location of 16
Do[
    m = MapAt[0&,m,p];                        Put a 0 at location p
    p = #& @@ MaximalBy[                      Set p to the member of
        p+#& /@ Tuples[{0,-1,1},2],             {all possible next locations}
        m~Extract~#&],                        that maximizes that element of m,
                                              ties broken by staying at p+{0,0}=p.
16];                                        Do this 16 times.
Tr[Tr/@m]                                   Finally, output the sum of m.
)&
```
[Answer]
Not the shortest solution, but pretty straight forward.
## Ruby, 207
```
a=eval(ARGV[0])
n=16
while n!=0 do
a[i=a.index(n)]=0
t=[a[i+4]]
t<<a[i-4]if i>3
if i%4!=0
t<<a[i-5]if i>3
t<<a[i-1]
t<<a[i+3]
end
if i%4!=3
t<<a[i+1]
t<<a[i+5]
t<<a[i-3]if i>3
end
n=t.compact.max
end
p a.sum
```
]