改变2-d迷宫求解器与1-d一起使用

时间:2013-11-21 16:40:45

标签: java recursion maze

考虑到包含构建迷宫的所有内容的代码,我要编写makeMove方法来解决迷宫,我已经完成并且工作正常。然而,一切都是为了使用迷宫和访问的二维数组,我需要编辑它与1-d阵列一起用于迷宫和访问。

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);
    }

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我假设您要将给定的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]完成的。您可以将其视为采用2D阵列并将行连接在一起以形成长1D阵列。

同样,visited数组可以声明为visited[MAX_COLS * MAX_ROWS]并通过visited[MAX_COLS * row + col]编入索引。