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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| const arr = [ [0,0,0,1,0], [0,1,1,1,0], [0,1,0,0,0], [0,0,0,1,0], [0,1,1,1,0] ]; const pathX = [1,-1,0,0]; const pathY = [0,0,-1,1]; let _arrLength = arr.length-1; let _arrElementLength = arr[0].length-1; let i=0,j=0; (function(){ console.time("time") arr[0][0] = 3; function matrix(i,j){ let k,newi,newj; for(k = 0;k<4;k++){ if (advance(i,j,k)) { 通过advance函数的判断返回一个可走的路的点 */ newi = i + pathX[k]; newj = j + pathY[k]; arr[newi][newj] = 3; 判断此时是否已经到了终点如果没有则递归 */ if (newi == _arrLength && newj == _arrElementLength) { end() } else { matrix(newi,newj); } } } arr[i][j] = 2 } matrix(0,0) function advance(i,j,k){ var bool = true; 每走一步路就判断其上下左右是否还有路可走 */ i += pathX[k]; j += pathY[k]; 判断临界范围,保证在迷宫范围内 */ if(i<0||i>_arrLength||j<0||j>_arrElementLength){ bool = false; }else if(arr[i][j]!=0){ bool = false; } return bool; } 负责输出结果 */ function end(){ let i,j,newArr=[]; for (i = 0; i < _arrLength+1; i++) { for (j = 0; j < _arrLength+1; j++) { if (arr[i][j] == 3) { newArr.push("V"); } else { newArr.push("*"); } } } 下面这段代码只是为了能够在控制台看得更直观,可无,因为写得有点笨拙 */ newArr.splice(0,0,"") newArr.splice(6,0,"\n"); newArr.splice(12,0,"\n"); newArr.splice(18,0,"\n"); newArr.splice(24,0,"\n"); console.log(newArr.join(" ")); } console.timeEnd("time") })()
|