Question
Please modify code to display a maze made up of '*' and display a path made up of '+': import java.util.LinkedList; import java.util.Queue; public class
Please modify code to display a maze made up of '*' and display a path made up of '+': import java.util.LinkedList; import java.util.Queue;
public class Maze { private char[][] maze; private boolean[][] visited; private int height; private int width;
public Maze(char[][] maze) { this.maze = maze; this.height = maze.length; this.width = maze[0].length; this.visited = new boolean[height][width]; }
public void escape(int startX, int startY) { Queue
visited[startX][startY] = true; queueX.add(startX); queueY.add(startY);
while (!queueX.isEmpty()) { int x = queueX.remove(); int y = queueY.remove();
if (x < 0 || x >= height || y < 0 || y >= width || visited[x][y] || maze[x][y] == '*') { // we have hit a wall or visited this cell before continue; }
// mark this cell as visited visited[x][y] = true;
if (y == width - 1) { // we have found the exit! maze[x][y] = '+'; System.out.println("Found the exit at (" + x + "," + y + ") and marked it with +"); break; }
// add unvisited neighbors to the queue queueX.add(x); queueY.add(y + 1); // right queueX.add(x); queueY.add(y - 1); // left queueX.add(x + 1); queueY.add(y); // down queueX.add(x - 1); queueY.add(y); // up }
// mark any unvisited cells as walls for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (!visited[i][j]) { maze[i][j] = '*'; } } }
// handle case where there is no path from starting point to exit if (!visited[height-1][width-1]) { System.out.println("There is no path from the starting point to the exit."); } }
public void printMaze() { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { System.out.print(maze[i][j] + " "); } System.out.println(); } } public static void main(String[] args) { char[][] m = { {'*', ' ', '*', '*', '*', '*', '*', '*', '*'}, {'*', ' ', ' ', ' ', ' ', ' ', '*', ' ', '*'}, {'*', ' ', '*', '*', '*', '*', '*', ' ', '*'}, {'*', ' ', '*', ' ', '*', ' ', ' ', ' ', '*'}, {'*', ' ', '*', ' ', '*', '*', '*', ' ', '*'}, {'*', ' ', ' ', ' ', '*', ' ', ' ', ' ', '*'}, {'*', '*', '*', ' ', '*', ' ', '*', ' ', '*'}, {'*', ' ', ' ', ' ', ' ', ' ', '*', ' ', '*'}, {'*', '*', '*', '*', '*', '*', '*', ' ', '*'} };
Maze maze = new Maze(m); maze.escape(0, 1); System.out.println("The path from the starting point to the exit is drawn with \"+\" below:"); for (int i = 0; i < maze.height; i++) { for (int j = 0; j < maze.width; j++) { System.out.print(maze.maze[i][j]); } System.out.println(); } } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started