JavaScript (ES6) 219
Una funzione che restituisce vero o falso. La soluzione (se trovata) viene emessa sulla console. Non cerca di trovare una soluzione ottimale.
f=o=>(r=(m,p,w=0,v=m[p])=>
v>':'
?console.log(' '+m.map(v=>v<0?'#':v,m[f]='X').join(' '))
:v<=w&&[1,-1,y,-y].some(d=>r([...m],d+p,v),m[p]='.')
)(o.match(/[^ ]/g).map((v,p)=>v>'S'?(f=p,0):v>':'?v:v<'0'?(y=y||~p,v):~v,y=0),f)
Ungolf a morte e ha spiegato più del necessario
f=o=>{
var r = ( // recursive search function
m, // maze array (copy of)
p, // current position
w // value at previous position
)=>
{
var v = m[p]; // get value at current position
if (v == 'S') // if 'S', solution found, output and return true
{
m[f] = 'X'; // put again 'X' at finish position
m = m.map(v => { // scan array to obtain '#'
if (v < 0) // a numeric value not touched during search
return '#'
else
return v
}).join(' '); // array to string again, with added blanks (maybe too many)
console.log(' '+m) // to balance ' '
return true; // return false will continue the search and find all possible solutions
}
if (v <= w) // search go on if current value <= previous (if numeric, they both are negative)
{
m[p]='.'; // mark current position
return [1,-1,y,-y].some(d=>r([...m], d+p, v)) // scan in all directions
}
// no more paths, return false and backtrack
return false
}
var f, // finish position (but it is the start of the search)
y = 0; // offset to next/prev row
o = o.match(/[^ ]/g) // string to char array, removing ' 's
.map((v,p) => // array scan to find f and y, and transform numeric chars to numbers
{
if (v > 'S') // check if 'X'
{
f = p;
return 0; // 'X' position mapped to min value
}
if (v > ':') // check if 'S'
return v; // no change
if (v < '0') // check if newline
{
if (!y) y = ~p; // position of first newline used to find y offset
return v; // no change
}
return ~v; // map numeric v to -v-1 so have range (-1..-10)
})
return r(o, f, 0) // start with a fake prev value
}
Test nella console Firefox / FireBug
f('3 3 3 3 2 1 S 8 9\n3 1 1 3 3 0 6 8 7\n1 2 2 4 3 2 5 9 7\n1 2 1 5 4 3 4 4 6\n1 1 X 6 4 4 5 5 5')
Produzione
. . . . # # S . #
. # # . . # # . .
. # # # . # # # .
. # # # . # # # .
. . X # . . . . .
true
S
eX
in qualsiasi direzione? Il labirinto è sempre risolvibile?