1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| function initRecord(N, M) { let arr = []; for (let i = 0; i < N; i++) { arr.push([]); for (let j = 0; j < M; j++) { arr[i].push(false); } } arr[0][0] = true; return arr; }
function Move(x, y, step) { this.x = x; this.y = y; this.step = step; }
function solution(A) { const N = A.length; const M = A[0].length; let record = initRecord(N, M); let dir = [ [2, -1], [2, 1], [1, -2], [1, 2], [-1, -2], [-1, 2], [-2, -1], [-2, 1] ]; let queue = [new Move(0, 0, 0)]; while (queue.length > 0) { let now = queue.shift(); if (now.x == N - 1 && now.y == M - 1) { return now.step; } for (let i = 0; i < dir.length; i++) { let mx = dir[i][0] + now.x; let my = dir[i][1] + now.y; if (mx >= 0 && mx < N && my >= 0 && my < M && (A[mx][my] != 1) && (record[mx][my] == false)) { record[mx][my] = true; queue.push(new Move(mx, my, now.step + 1)); } } } return -1; }
var A = [ [0, 0, 0], [0, 0, 1], [1, 0, 0], [0, 0, 0], ]; console.log(solution(A)); // 7
|