走出迷宫

时间:2021-07-10 15:24:34

标签: javascript

II 需要写一个算法来找出迷宫的出路,也就是二维数组。我玩过代码,但它不能完全理解我应该如何在代码中标记终点线,当没有更多的加号时,这是远离迷宫的一种方式? 0 - 起始位置 + - 方式 # - 墙。

我在正确的轨道上吗?递归函数是应对这一挑战的好方法吗?

var maze = [
  ['#', '#', '#', '#', '#', '#', '#', '#', '#', '#'],
  ['#', '#', '#', '#', '#', '#', '#', '#', '#', '#'],
  ['#', '#', '+', '+', '#', '#', '#', '#', '#', '#'],
  ['#', '#', '+', '#', '0', '#', '+', '+', '+', '+'],
  ['#', '#', '+', '+', '+', '+', '+', '#', '#', '#'],
  ['#', '#', '#', '#', '#', '+', '+', '#', '#', '#'],
  ['#', '#', '#', '#', '#', '#', '+', '#', '#', '#'],
  ['#', '#', '#', '#', '#', '#', '+', '#', '#', '#'],
  ['#', '#', '#', '#', '#', '#', '+', '+', '#', '#'],
  ['#', '#', '#', '#', '#', '#', '#', '#', '#', '#']
];

我玩过代码但仍然无法完全获得它?我在正确的路上吗?递归函数可以解决这个挑战吗?我非常感谢所有能帮助我的人。

我的“不完美的代码”:)

function goFurther(row, column) {

  console.log(maze[row][column]);
  if (maze[row][column] == ' ') {
    console.log('We solved the maze');
  } else if (maze[row][column] == '+') {
    console.log('you need make it go further');
    maze[row][column] = 909;
    if (row < maze.length - 1) {
      goFurther(row + 1, column);
    }
    if (column < maze[row].length - 1) {
      goFurther(row, column + 1);
    }

    if (row > 0) {
      goFurther(column + 1, row);
      console.log(row, column);
    }
    if (column > 0) {
      goFurther(row + 1, column);
      console.log(row, column);
    }
  }
}

goFurther(2, 2);

0 个答案:

没有答案
相关问题