JSFiddle - React, Tailwind, and code Playground
Graph problem. Search shortest path to target.
Target is at 9, 1 means allowed route, 0 means not allowed route. Correct answers are in comments.
by Yurii Predborskyi
JavaScript
let arr1 = [
[1,0,0],
[1,0,0],
[1,9,0],
]; // 3
let arr2 = [
[1,0,0,1],
[1,1,1,0],
[1,0,1,9],
]; // 5
let arr3 = [
[1,0,9],
[1,0,1],
[0,1,1],
]; // -1
function calculateDistance(field) {
function addToQueue(q, x, y, len) {
if (x < 0 || x >= field.length) return;
if (y < 0 || y >= field[0].length) return;
if (field[x][y] === 0) return;
// console.log(`considering adding [${x}][${y}], field x y is`, field[x]);
q.push([x, y, len + 1]);
}
let q = [[0,0,0]];
while (q.length > 0) {
// console.log('queue is ', q);
let [x, y, len] = q.shift();
if (field[x][y] === 9) return len; // target found
field[x][y] = 0; // prevent visiting nodes twice
addToQueue(q, x-1, y, len);
addToQueue(q, x, y-1, len);
addToQueue(q, x+1, y, len);
addToQueue(q, x, y+1, len);
}
return -1;
}
console.log('3 =', calculateDistance(arr1));
console.log('5 =', calculateDistance(arr2));
console.log('-1 =', calculateDistance(arr3));