给定包含构建迷宫的所有内容的代码,我将编写 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/