changing 2-d maze solver to be used with 1-d

安稳与你 提交于 2019-12-13 20:25:48

问题


Given code that included everything to build a maze, I was to write the makeMove method to solve the maze, which I have completed and is working fine. However everything is done to use 2-D array with the maze and visited, I need to edit this to be used with 1-d array for maze and visited.

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

Do I need to change every place where maze[][] is and visited[][]? What is the simplest way to go about this?

Thanks for any and all help!


回答1:


I assume that you want to change the given 2D maze array into a 1D maze class member. Declare the maze member as

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

You can index this array as maze[COLS * row + col]. You'll then need to copy the elements over:

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

As you can see, accessing an element is accomplished via this.maze[COLS * r + c] instead of this.maze[r][c]. You can think of it as taking the 2D array and joining the rows together to form a long 1D array.

Similarly, the visited array can be declared as visited[MAX_COLS * MAX_ROWS] and indexed via visited[MAX_COLS * row + col].



来源:https://stackoverflow.com/questions/20126813/changing-2-d-maze-solver-to-be-used-with-1-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!