Java Maze Shortest Path误解

时间:2015-12-27 10:47:54

标签: java arrays function recursion shortest-path

这是代码,使用递归,我试图解决最短路径的迷宫,但它用更长的方式解决,我真的不明白为什么。这是递归代码:

public boolean findPath(int row, int col) {
board[row][col].visit();

if ((col == 7) && (row == 7)) {
  board[row][col].selectCell();
  return true;
}


if ((row > 0) && !board[row - 1][col].marked() &&
    !board[row - 1][col].blocked() && !board[row - 1][col].visited()) {
  block(row, col);

  if (findPath(row - 1, col)) {
    board[row][col].selectCell();
    return true;
  }

  unblock(row, col);
}

if ((row < 7) && !board[row + 1][col].marked() &&
    !board[row + 1][col].blocked() && !board[row + 1][col].visited()) {
  block(row, col);

  if (findPath(row + 1, col)) {
    board[row][col].selectCell();
    return true;
  }

  unblock(row, col);
}

if ((col > 0) && !board[row][col - 1].marked() &&
    !board[row][col - 1].blocked() && !board[row][col - 1].visited()) {
  block(row,col);
  if (findPath(row, col - 1)) {
    board[row][col].selectCell();
    return true;
  }

  unblock(row,col);
}

if ((col < 7) && !board[row][col + 1].marked() &&
    !board[row][col + 1].blocked() && !board[row][col + 1].visited()) {
  block(row,col);
  if (findPath(row, col + 1)) {
    board[row][col].selectCell();
    return true;
  }

  unblock(row,col);
}

return false;

}

它是8x8板,块功能如下:

public void block(int row, int col) {
if (row > 0) {
  board[row - 1][col].block();
}

if (row < 7) {
  board[row + 1][col].block();
}

if (col > 0) {
  board[row][col - 1].block();
}

if (col < 7) {
  board[row][col + 1].block();
}

}

当我尝试解决它时,给我这样的东西: enter image description here

代替: enter image description here

任何帮助都会非常适合!

1 个答案:

答案 0 :(得分:2)

试试这个,它应该可以工作并直接完成:

public boolean findPath(int row, int col) {
  board[row][col].visit();

  if ((col == 7) && (row == 7)) {
    board[row][col].selectCell();
    return true;
  }

  if ((row < 7) && !board[row + 1][col].marked() &&
      !board[row + 1][col].blocked() && !board[row + 1][col].visited()) {
    block(row, col);

    if (findPath(row + 1, col)) {
      board[row][col].selectCell();
      return true;
    }

    unblock(row, col);
  }

  if ((col > 0) && !board[row][col - 1].marked() &&
      !board[row][col - 1].blocked() && !board[row][col - 1].visited()) {
    block(row,col);

    if (findPath(row, col - 1)) {
      board[row][col].selectCell();
      return true;
    }

    unblock(row,col);
  }

  if ((col < 7) && !board[row][col + 1].marked() &&
      !board[row][col + 1].blocked() && !board[row][col + 1].visited()) {
    block(row,col);

    if (findPath(row, col + 1)) {
      board[row][col].selectCell();
      return true;
    }

    unblock(row,col);
  }
  if ((row > 0) && !board[row - 1][col].marked() &&
      !board[row - 1][col].blocked() && !board[row - 1][col].visited()) {
    block(row, col);

    if (findPath(row - 1, col)) {
      board[row][col].selectCell();
      return true;
    }

    unblock(row, col);
  }

  return false;
}

您需要更改订单。