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
| class MazeQuest {
constructor(maze, start, end) { this.maze = maze this.start = start this.end = end this.dirs = [ [0, 1], [0, -1], [-1, 0], [1, 0] ] this.run(start, end) }
mark(pos) { this.maze[pos[0]][pos[1]] = 2 }
isEqual(pos1, pos2) { if (pos1[0] === pos2[0] && pos1[1] === pos2[1]) { return true } else { return false } }
passable(pos) { if (pos[0] < 0 || pos[1] < 0) { return false } else if ( this.maze.length <= pos[0] || this.maze[pos[0]].length <= pos[1] ) { return false } return this.maze[pos[0]][pos[1]] == 0 }
run(start, end) { this.mark(start) if (this.isEqual(start, end)) { console.log(`找到出口: ${start}`) return true }
this.dirs.forEach(item => { let pos = [start[0] + item[0], start[1] + item[1]] if (this.passable(pos)) { console.log(`移动位置: ${pos}`) if (this.run(pos, end)) { return true } } }) return false } }
;(function main() { let maze = [ [0, 0, 0, 1, 1], [0, 1, 0, 0, 1], [0, 0, 1, 0, 0], [1, 0, 0, 1, 1], [1, 1, 0, 0, 0] ] console.log('迷宫地图:') console.log(maze) new MazeQuest(maze, [0, 0], [4, 4]) })()
|