使用 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.