如何使用算法 BFS 找到寻找 E 的短路径,但 solve() 函数返回 -1

问题描述 投票:0回答:0

有没有我遗漏的错误或错误?

const grid = [
  ['#', '#', '#', '#', '#', '#', '#'],
  ['#', '.', '.', '.', '.', '.', '#'],
  ['#', '.', '#', '#', '#', '.', '#'],
  ['#', '.', '#', 'E', '#', '.', '#'],
  ['#', '.', '#', '#', '#', '.', '#'],
  ['#', '.', '.', '.', '.', '.', '#'],
  ['#', '#', '#', '#', '#', '#', '#']
]

const sR = 0;
const sC = 0;

move_count = 0;
node_left = 1;
node_next = 0;

reached_end = false;

const visited = Array.from({
  length: grid.length
}, () => Array(grid[0].length).fill(false));

const rq = [];
const cq = [];

const dr = [-1, 1, 0, 0]
const dc = [0, 0, -1, 1]

function solve() {
  rq.push(sR);
  cq.push(sC);
  visited[sR][sC] = true;

  while (rq.length > 0 || cq.length > 0) {
    var r = rq.shift();
    var c = cq.shift();
    if (grid[r][c] === "E") {
      reached_end = true;
      break;
    }
    explore_neighbors(r, c)
    node_left--
    if (node_left === 0) {
      node_left = node_next
      node_next = 0
      move_count++
    }
  }
  if (reached_end) {
    return move_count;
  } else {
    return -1
  }
}

function explore_neighbors(r, c) {
  for (let i = 0; i < 4; i++) {
    let rr = r + dr[i];
    let cc = c + dc[i];

    if (rr > 0 || cc > 0) continue;
    if (rr < grid.length - 1 || cc < grid[0].length - 1) continue;

    if (visited[rr][cc]) continue;
    if (grid[rr][cc] == "#") continue;

    rq.push(rr);
    ca.push(cc);
    visited[rr][cc] = true;
    node_next++
  }
}

let bfs = solve()
console.log(bfs);

块引用 我试图在上面找到寻找 E 表格网格 arr 的捷径,但我的代码没有显示正确答案并返回 -1,我认为我的函数 solve() 应该返回另一个数字作为捷径是否有任何错误或问题或者我想念的东西?

javascript algorithm depth-first-search breadth-first-search
© www.soinside.com 2019 - 2024. All rights reserved.