题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// 这道题目说的是只能横着走或者竖着走,没说只能向下或者向右,所以这道题向左或者向上走都是可以的,这里面临的问题就是可能会走到已经走过的地方(这里会无限循环下去,如果可以走回头路)。所以需要给每个走过的地方都标记,不允许再次走
function test(arr) {
  let ans = [];
  let i = 0,
    j = 0;
  function dfs(i, j) {
    if(i < 0 || i > arr.length - 1 || arr[i][j] === 1 || arr[i][j] === undefined){
      return
    }
    ans.push(`(${i},${j})`);
    arr[i][j]=1 // 这里将遍历过的每个元素掷为1,也就是标记了已经走过的意思,下次不允许再走回头路。
    if (i === arr.length - 1 && j === arr[0].length - 1) {
      for (const item of ans) {
        console.log(item);
      }
      return;
    }
    let index = ans.length - 1;
    dfs(i, j + 1); // 向右走
    ans.splice(index + 1);
    dfs(i + 1, j); // 向下走
    ans.splice(index + 1);
    dfs(i-1, j); // 向上走
    ans.splice(index + 1);
    dfs(i, j-1); // 向左走
    ans.splice(index + 1);
  }
  dfs(0, 0);
}

const arr = [];
rl.on("line", function (line) {
  arr.push(line.split(" ").map((item) => parseInt(item)));
});
rl.on("close", function () {
  arr.shift()
  test(arr);
});

全部评论

相关推荐

1 1 评论
分享
牛客网
牛客企业服务