java - 更改二维迷宫求解器以与一维迷宫一起使用

标签 java recursion maze

给定包含构建迷宫的所有内容的代码,我将编写 makeMove 方法来解决迷宫,我已经完成了该方法并且工作正常。然而,一切都是为了将​​二维数组与迷宫和访问一起使用,我需要编辑它以与迷宫和访问的一维数组一起使用。

public abstract class AbstractMaze {

protected int startRow;   // starting row
protected int startCol;   // starting column
protected int endRow;     // ending row
protected int endCol;     // ending column

/**
 * Declare the maze, 1's are walls and 0's are open
 */
protected int[][] maze;

protected AbstractMaze(int[][] maze, int startRow, int startCol, int endRow, int endCol) {
    super();
    this.maze = maze;
    this.startRow = startRow;
    this.startCol = startCol;
    this.endRow = endRow;
    this.endCol = endCol;
}
public void solve() {
    makeMove( startRow, startCol )
}
protected abstract void makeMove( int row, int col );
}
<小时/>
public class Maze2 extends AbstractMaze
 {
public Maze2(int[][] maze, int startRow, int startCol, int endRow, int endCol) {
    super(maze, startRow, startCol, endRow, endCol);
}
int MAX_ROWS = endRow + 1;
int MAX_COLS = endCol + 1;
boolean[][]visited = new boolean[MAX_ROWS][MAX_COLS];
protected void makeMove( int row, int col )
{
    boolean found = false;
    if (row < 0 || row >= MAX_ROWS  || col < 0 || col >= MAX_COLS  || visited[row][col] || maze[row][col] == 1)
        return;

    visited[row][col] = true;
    found = row == endRow && col == endCol;

    if (!found) {
        makeMove(row, col - 1);
        makeMove(row, col + 1);
        makeMove(row - 1, col);
        makeMove(row + 1, col);
    }

我需要更改迷宫[][]所在和访问过[][]的每个地方吗?最简单的方法是什么?

感谢您的帮助!

最佳答案

我假设您想要将给定的 2D maze 数组更改为 1D maze 类成员。将 maze 成员声明为

int ROWS = maze.length;
int COLS = maze[0].length;
this.maze = new int[ROWS * COLS];

您可以将此数组索引为maze[COLS * row + col]。然后,您需要将元素复制到:

for (int r = 0; r < ROWS; r++)
    for (int c = 0; c < COLS; c++)
        this.maze[COLS * r + c] = maze[r][c];

如您所见,访问元素是通过 this.maze[COLS * r + c] 而不是 this.maze[r][c] 完成的。您可以将其视为采用二维数组并将行连接在一起形成一个长的一维数组。

类似地,visited 数组可以声明为 visited[MAX_COLS * MAX_ROWS] 并通过 visited[MAX_COLS * row + col] 进行索引。

关于java - 更改二维迷宫求解器以与一维迷宫一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20126813/

相关文章:

java - 回顾基于 RMI 的身份验证方法

python - Python 中的指数递归

java - 使用广度优先搜索算法存储迷宫求解路径

C++迷宫计数通过时间

c# - 如何跟踪所有线程的完成。 C#

java - 通过迷宫(地牢)的最快路径 Dijstkra

java - HashMap 到 csv/excel 很容易吗?

java - 在 JUnit 5 中使用 Allure 进行测试报告

java - 如何使用 Ant 将 jsp 预编译的 web.xml 片段与主 web.xml 合并

Java - 数字的递归和及其工作原理