Question: Intro to JAVA please see below thank you! ------------------------------------------------------------------- In order to escape from a maze, you first need to find out where you can
Intro to JAVA please see below thank you!
-------------------------------------------------------------------
In order to escape from a maze, you first need to find out where you can move from a given location. We represent a maze as a two-dimensional array of characters, where the walls are marked by * characters and corridors by spaces. Given a position in the maze, print out the free neighbors to the north, west, south, and east. Complete the following code:
CODE:
import java.util.Scanner;
/** A maze has its walls marked by * characters and corridors by spaces. */ public class Maze { public static void main(String[] args) { char[][] maze = makeMaze( "***************************** " + "** *** * " + "** *** * ******************** " + "** *** * * * " + "** *** * ***** * ********** " + "** * ******************** " + "****** *************** ****** " + "****** ******* ****** " + "* ******* ******* ****** " + "* **** ******* ** * " + "* * ******* ******* ****** " + "* **** ******* *** ****** " + "************** ************** ");
Scanner in = new Scanner(System.in); System.out.print("Row: "); int row = in.nextInt(); System.out.print("Column: "); int col = in.nextInt(); // Print free neighbors if (. . .) // North { System.out.println(. . . + " " + . . .); } if (. . .) // West { System.out.println(. . . + " " + . . .); } if (. . .) // South { System.out.println(. . . + " " + . . .); } if (. . .) // East { System.out.println(. . . + " " + . . .); } }
/** Constructs a maze from a string describing its contents. @param contents a string consisting of *, spaces, and newlines terminating the rows. */ public static char[][] makeMaze(String contents) { int rows = 0; int columns = 0; int currentLength = 0; for (int i = 0; i < contents.length(); i++) { if (contents.charAt(i) == ' ') { columns = Math.max(columns, currentLength); currentLength = 0; rows++; } else { currentLength++; } } char[][] cells = new char[rows][columns]; int row = 0; int column = 0; for (int i = 0; i < contents.length(); i++) { if (contents.charAt(i) == ' ') { row++; column = 0; } else { cells[row][column] = contents.charAt(i); column++; } } return cells; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
