使用 JavaScript 寻找迷宫出口路径


问题

我们要求编写一个 JavaScript 函数,它接受一个 N * N 阶矩阵。矩阵中的墙壁标记为“W”,空位置标记为“_”

在任何时候我们都可以向四个方向中的任何一个方向移动。如果我们可以到达最后 [N - 1, N - 1],则我们的函数应该返回 true,否则返回 false。

示例

以下代码演示了这一点 −

 实时演示

const maze = [
   ['_', 'W', 'W', 'W'],
   ['_', 'W', 'W', 'W'],
   ['W', '_', '_', 'W'],
   ['W', 'W', 'W', '_']
];
const canFindPath = (m = []) => {
   let h = m.length;
   let w = m[0].length;
   let queue = [[0, 0]];
   let mark = (xx, yy) => {
      [[1, 0], [-1, 0], [0, 1], [0, -1], [0, 0]].map(p => {
         let [x, y] = [p[0]+xx, p[1]+yy];
         if (0 <= x && x < w) {
            if (0 <= y && y < h) {
               if (m[y][x] === '.') {
                  m[y][x] = '#';
                  queue.push([x, y]);
               }
            }
         }
      });
   };
   do {
      let p = queue.shift();
      mark(...p);
   } while (queue.length);
   return m[h-1][w-1] !== '.';
};
console.log(canFindPath(maze));

输出

true

更新日期:2021 年 4 月 17 日

212 次浏览

开启您的职业生涯

完成该课程以获得认证

开始
广告
© . All rights reserved.