JSFiddle - React, Tailwind, and code Playground
by BaliBalo
JavaScript
var w = 6, h = 6;
var mat = [
2,2,1,1,1,1,
1,2,1,1,1,3,
1,1,3,1,1,1,
1,1,2,1,2,2,
1,3,1,1,1,1,
3,1,1,2,1,1 ];
var init = {x: 0, y: 3}, end = {x: 5, y: 2};
function posToInt(pos, w) { return pos.y * w + pos.x; }
function checkEmpty(t){for(var i=t.length;i-- && !t[i];);return i<0;}
function test(pos, mat, end, path, dir)
{
var posi = posToInt(pos, w),
val = mat[posi];
if( pos.x < 0 || pos.x >= w
|| pos.y < 0 || pos.y >= h
|| !val)
return [];
dir = dir || [];
path = (path || []).concat(posi);
var newMat = mat.slice(0);
newMat[posi] = 0;
if(checkEmpty(newMat))
{
if(pos.x == end.x && pos.y == end.y)
return [dir];
else
return [];
}
else
{
return test({x: pos.x + val, y: pos.y}, newMat, end, path, dir.concat('D'))
.concat(test({x: pos.x - val, y: pos.y}, newMat, end, path, dir.concat('G')))
.concat(test({x: pos.x, y: pos.y + val}, newMat, end, path, dir.concat('B')))
.concat(test({x: pos.x, y: pos.y - val}, newMat, end, path, dir.concat('H')));
}
}
console.log(test(init, mat, end));