Complete the Mazer practice problem before reviewing the solution.

Review the Mazer solution with AP CS Tutor Brandon Horn.

Part (a)

public Mazer(int rows, int cols)
{
    maze = new String[rows][cols];

    for(int row = 0; row < maze.length; row++)
    {
        for(int col = 0; col < maze[0].length; col++)
        {
            if(col == 0 || maze[row][col - 1] == null)
            {
                double randNum = Math.random();

                if(randNum < 0.1)
                    maze[row][col] = "|";
                else if(randNum < 0.3)
                    maze[row][col] = "/";
                else if(randNum < 0.5)
                    maze[row][col] = "\\";
            }
        }
    }
}

Part (b)

public boolean willWin(int startRow)
{
    int playerRow = startRow;

    for(int playerCol = 0; playerCol < maze[0].length; playerCol++)
    {
        String obstacle = maze[playerRow][playerCol];
        if(obstacle != null)
        {
            if(obstacle.equals("|"))
                return false;
            else if(obstacle.equals("\\"))
                playerRow++;
            else if(obstacle.equals("/"))
                playerRow--;

            if(playerRow < 0 || playerRow >= maze.length)
                return false;
        }
    }

    return true;
}

Additional 2D array resources

Comments

Comment on Mazer free response