SlideShare a Scribd company logo
1 of 9
Download to read offline
Topic: Use stacks to solve Maze. DO NOT USE RECURSION. And do not use hashmaps
Position.java
public class Position {
/***************************
* Attributes
****************************/
private int row;
private int column;
/***************************
* Constructor
*
* @param row
* @param column
***************************/
public Position(int row, int column) {
this.row = row;
this.column = column;
}
/**************************
* Checks two positions for equality. Two positions are equal if the have the
* same row and column numbers.
*************************/
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Position)) {
return false;
}
Position otherPosition = (Position) obj;
return (otherPosition.row == row && otherPosition.column == column);
}
public String toString() {
return "row:" + row + " column:" + column;
}
/**************************
* Getter and Setter methods
*
* @return
*/
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
Maze.java
public class Maze {
/**
* Two dimensional array to represent a maze
*/
private final char[][] maze;
private final Position start, end;
/**
* Constructor initializing the maze array
*
* @param maze
*/
public Maze(char[][] maze, Position start, Position end) {
this.maze = maze;
if (validPosition(start)) {
this.start = start;
} else {
throw new PositionNotValidException("The start position is valid for the maze: " + start);
}
if (validPosition(end)) {
this.end = end;
} else {
throw new PositionNotValidException("The stop position is valid for the maze: " + end);
}
}
/**
* Returns the start position object.
*
* @return The start position.
*/
public Position getStart() {
return start;
}
/**
* Returns the stop position object.
*
* @return
*/
public Position getEnd() {
return end;
}
/**
* Returns the number of rows the maze has.
*
* @return The number of rows.
*/
public int numRows() {
return maze.length;
}
/**
* Returns the number of columns the row of the maze has.
*
* @param row The row to get the length of.
* @return The length of the row in the maze.
*/
public int numCols(int row) {
return maze[row].length;
}
/**
* Tests if row and column are valid within the two dimensional array. Will
* return true iff row is between 0 and maze.length-1 and column is between 0
* and maze[row].length - 1.
*
* @param row Represents the array to retrieve from maze.
* @param col Represents the character to retrieve from the array at maze[row].
* @return True iff the row and column are valid indices of maze otherwise
* false.
*/
public boolean validPosition(int row, int col) {
if (row >= 0 && row < maze.length) {
if (col >= 0 && col < maze[row].length) {
return true;
}
}
return false;
}
/**
* Tests if the row and column stored in pos are valid. Drops to the
* validPosition(int row, int col) method.
*
* @param pos The position to test.
* @return True iff pos is valid inside the maze otherwise false.
*/
public boolean validPosition(Position pos) {
return validPosition(pos.getRow(), pos.getColumn());
}
/**
* Returns the character at pos.
*
* @param pos The position to retrieve the character at.
* @return The character at maze[pos.row][pos.column]
* @throws PositionNotValidException if the position is now within the maze.
*/
public char getAt(Position pos) {
if (validPosition(pos)) {
return maze[pos.getRow()][pos.getColumn()];
} else {
String msg = String.format("The position given is not valid: %s", pos.toString());
throw new PositionNotValidException(msg);
}
}
/**
* Retrieves the character at maze[row][column].
*
* @param row The row to retrieve the character from.
* @param column The column to retrieve the character from.
* @return The character at position row, column
* @throws PositionNotValidException if the row or column are not within bounds.
*/
public char getAt(int row, int column) {
if (validPosition(row, column)) {
return maze[row][column];
} else {
String msg = String.format("The row and column given is not valid: row %d col %d", row,
column);
throw new PositionNotValidException(msg);
}
}
/**
* Sets a character at a specified position.
*
* @param pos The position to set the character at.
* @param c The character to set at position.
* @throws PositionNotValidException if the position passed in is not valid
* within the maze.
*/
public void setAt(Position pos, char c) {
if (validPosition(pos)) {
setAt(pos.getRow(), pos.getColumn(), c);
} else {
String msg = String.format("The position given is not valid: %s", pos.toString());
throw new PositionNotValidException(msg);
}
}
/**
* Sets a character at a specified row and column.
*
* @param pos The position to set the character at.
* @param c The character to set at position.
* @throws PositionNotValidException if the position passed in is not valid
* within the maze.
*/
public void setAt(int row, int column, char c) {
if (validPosition(row, column)) {
maze[row][column] = c;
} else {
String msg = String.format("The row and column given is not valid: row %d col %d", row,
column);
throw new PositionNotValidException(msg);
}
}
/*** METHODS NOT NEEDED TO HELP SOLVE THE PROBLEM. ****/
/*** YOU DO NOT NEED TO USE THESE METHODS AS THEY ****/
/*** ARE USED IN THE MAIN CLASS. ****/
public Maze clone() {
char clone[][] = new char[maze.length][];
for (int r = 0; r < maze.length; r++) {
clone[r] = new char[maze[r].length];
for (int c = 0; c < maze[r].length; c++) {
clone[r][c] = maze[r][c];
}
}
return new Maze(clone, start, end);
}
public String toString() {
StringBuffer sb = new StringBuffer();
for (int r = 0; r < maze.length; r++) {
sb.append(maze[r]);
sb.append("n");
}
return sb.toString();
}
}
MazeSolver.java - ONE THAT I NEED A HELP WITH!!
import java.util.Stack;
/**
* Notes:
*
* The start and end position are contained within the maze object. Use the
* getStart() and getEnd() methods.
*
*/
public class MazeSolver {
/**
* You need to implement this method
*
* @param maze: The maze to be solved.
* @return An array of Position which stores a solution to the maze. If a
* solution is not found a null value should be returned.
*/
public static Position[] solve(Maze maze) {
return null;
}
} Consider a maze made up of rectangular array of squares, such as the following one: rigure 1--
A sampie maze The " X " blocks represent a blocked square and form the walls of the maze. Let
us consider mazes that have only one entrance and one exit, as in our example. Beginning at the
entrance at the top left side of the maze, find a path to the exit at the bottom right side. You can
move only up, down, left, or right. Square is either clear or blocked by an X character. Let a two-
dimensional array represent the maze. Use a stack data structure to find a path through the maze.
Some mazes might have more than one successful path, while others might have no path. Hints: -
The primary consideration is that if you reach a dead end, you need to be able to backtrack along
the path to the point where you can try a different path. The stack data structure makes it possible
to store the current path and backtrack if necessary. Every clear position visited in the current
path is pushed to the stack and if a dead end is reached, the previous position is popped from the
stack to backtrack. You need to have a loop that begins with the start position and pushes it into
the stack then moves to a neighboring cell until either the goal position is reached, or the stack
becomes empty. - Make sure to mark each clear array cell you move to as visited to avoid
checking it again and getting stuck in an infinite loop. For example, each array cell can have
three different values: " " for blocked, "V" for visited, and " "for clear. - A dead end is an array
cell whose all neighbors are either blocked or already visited.
There are four files you should pay attention to: - Position.java: a class to store the position of an
array cell. It has two attributes: row and column along with their accessor and mutator methods.
It also has an equal's method that checks for equality of two Position objects. - Maze.java: a class
to store a maze. It has 3 attributes: a two-dimensional character array which represents the maze,
a Position object to represent the start location, and another Position object to represent the stop
location. - MazeSolver: This class contains one static method, solve. It accepts a maze and
returns an array of Positions that is used to traverse the maze if the maze is solvable. If the maze
is not solvable then an empty array is returned. - Keep in mind that stacks store objects in reverse
order so be sure to return the position array in the correct order. - Tester: a sample driver class
which calls the traverse method on a maze in either the SolvableMaze, UnsolvableMaze, or
HugeSolvableMaze files. These should be at the root of the project folder. You only need to
implement the solve method in the MazeSolver.java class. This method receives the maze to
solve as a parameter and returns an array of Position objects which stores a solution to the maze
if such solution exists; otherwise, it returns an empty array. Note: There might be more than one
possible solution to a maze, depending on the ordering in which the neighboring cells are visited
at each location. You can do whatever order you want if the maze is solved. For instance, First
move left, if the left neighbor is not clear, then move right, if the right neighbor is not clear, then
move up, if it is not clear, then move down. You may create any additional helper methods to aid
you. For instance, you may make a method to convert the stack to a necessary array. Just
remember, when you grab the information from a stack you are getting in the reverse order you
push them. You must solve the problem using a Stack. You may use the built-in stack library but
use of any other data structure is prohibited apart from constructing the final Position array
result. Recursion is also not allowed. What you need to turn in: You need to submit the
MazeSolver.java file containing your implementation of the solve method.
Additional Notes and Helpful Hints First hint I have is to not be afraid of creating additional
variables to store information. For instance, you must move up, down, left, and right (or north,
south, west, and east). Creating Position objects to represent these movements is perfectly
acceptable. You will also want to create an object that is the walker of the maze. This walker
keeps the current position in the maze. Other than push, pop, and peek on the Stack class,
isEmpty is also a useful method. The maze class contains a bunch of methods that is meant to
help you. Read what the methods do and decide which ones you want to use for your solution.
Read the code given to you FIRST before starting to write your code so you can utilize it. It is
there to make your life easier, not harder. Try to translate what you want to do in terms of the
stack operations. For instance, if you find yourself at a dead end then you want to move back to a
previous position. This means you will need to first pop the top position, which contains the spot
located at the dead end, then peek to see where you need to be. Your stack should be declared
and initialized as such: Stack> _ Give it a name _ = new Stack < Position =(); where you can
name it whatever you want. Moving in a two-dimensional array requires the following math:

More Related Content

Similar to Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf

08 recursive backtracking
08 recursive backtracking08 recursive backtracking
08 recursive backtrackingOmar Shahid
 
Section4 union of classes and methods
Section4 union of classes and methodsSection4 union of classes and methods
Section4 union of classes and methodsDương Tùng
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)Tak Lee
 
Java Question Consider a maze made up of a rectangular array of squ.pdf
Java Question Consider a maze made up of a rectangular array of squ.pdfJava Question Consider a maze made up of a rectangular array of squ.pdf
Java Question Consider a maze made up of a rectangular array of squ.pdfwasemanivytreenrco51
 
16 Java Regex
16 Java Regex16 Java Regex
16 Java Regexwayn
 
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfArjunSingh81957
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxshericehewat
 
Please make the complete program, Distinguish between header files a.pdf
Please make the complete program, Distinguish between header files a.pdfPlease make the complete program, Distinguish between header files a.pdf
Please make the complete program, Distinguish between header files a.pdfSALES97
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfdbrienmhompsonkath75
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework HelpC++ Homework Help
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascriptMD Sayem Ahmed
 
Getting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdfGetting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdfmohammedfootwear
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
You are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfYou are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfeyebolloptics
 

Similar to Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf (20)

08 recursive backtracking
08 recursive backtracking08 recursive backtracking
08 recursive backtracking
 
Section4 union of classes and methods
Section4 union of classes and methodsSection4 union of classes and methods
Section4 union of classes and methods
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
Java Question Consider a maze made up of a rectangular array of squ.pdf
Java Question Consider a maze made up of a rectangular array of squ.pdfJava Question Consider a maze made up of a rectangular array of squ.pdf
Java Question Consider a maze made up of a rectangular array of squ.pdf
 
16 Java Regex
16 Java Regex16 Java Regex
16 Java Regex
 
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdfSorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
Sorting-algorithmbhddcbjkmbgjkuygbjkkius.pdf
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Please make the complete program, Distinguish between header files a.pdf
Please make the complete program, Distinguish between header files a.pdfPlease make the complete program, Distinguish between header files a.pdf
Please make the complete program, Distinguish between header files a.pdf
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdf
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework Help
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
Getting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdfGetting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdf
 
Functional sudoku
Functional sudokuFunctional sudoku
Functional sudoku
 
Java session4
Java session4Java session4
Java session4
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
You are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfYou are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdf
 

More from ambikacollection1084

Un grupo de investigadores est� estudiando el oper�n WOLF, que se en.pdf
Un grupo de investigadores est� estudiando el oper�n WOLF, que se en.pdfUn grupo de investigadores est� estudiando el oper�n WOLF, que se en.pdf
Un grupo de investigadores est� estudiando el oper�n WOLF, que se en.pdfambikacollection1084
 
Un hombre de 28 a�os ten�a varias quejas. Ten�a un caso grave de aft.pdf
Un hombre de 28 a�os ten�a varias quejas. Ten�a un caso grave de aft.pdfUn hombre de 28 a�os ten�a varias quejas. Ten�a un caso grave de aft.pdf
Un hombre de 28 a�os ten�a varias quejas. Ten�a un caso grave de aft.pdfambikacollection1084
 
Un grupo de procesos que busca combinar las caracter�sticas y vent.pdf
Un grupo de procesos que busca combinar las caracter�sticas y vent.pdfUn grupo de procesos que busca combinar las caracter�sticas y vent.pdf
Un grupo de procesos que busca combinar las caracter�sticas y vent.pdfambikacollection1084
 
Un gobierno decide donar a perpetuidad con pagos anuales debido a un.pdf
Un gobierno decide donar a perpetuidad con pagos anuales debido a un.pdfUn gobierno decide donar a perpetuidad con pagos anuales debido a un.pdf
Un gobierno decide donar a perpetuidad con pagos anuales debido a un.pdfambikacollection1084
 
Un estudio de caso de marca compartida Escribir un correo electr�n.pdf
Un estudio de caso de marca compartida Escribir un correo electr�n.pdfUn estudio de caso de marca compartida Escribir un correo electr�n.pdf
Un estudio de caso de marca compartida Escribir un correo electr�n.pdfambikacollection1084
 
Un escenario Mary trabaja en el departamento de gesti�n de informaci.pdf
Un escenario Mary trabaja en el departamento de gesti�n de informaci.pdfUn escenario Mary trabaja en el departamento de gesti�n de informaci.pdf
Un escenario Mary trabaja en el departamento de gesti�n de informaci.pdfambikacollection1084
 
un desarrollador acord� pagar la infraestructura de agua y aguas res.pdf
un desarrollador acord� pagar la infraestructura de agua y aguas res.pdfun desarrollador acord� pagar la infraestructura de agua y aguas res.pdf
un desarrollador acord� pagar la infraestructura de agua y aguas res.pdfambikacollection1084
 
Un estudio de 2015 de hospitales, plantas de energ�a y servicios de .pdf
Un estudio de 2015 de hospitales, plantas de energ�a y servicios de .pdfUn estudio de 2015 de hospitales, plantas de energ�a y servicios de .pdf
Un estudio de 2015 de hospitales, plantas de energ�a y servicios de .pdfambikacollection1084
 
Un endoso es la firma del tenedor. pagador. editor. caj�n..pdf
Un endoso es la firma del tenedor. pagador. editor. caj�n..pdfUn endoso es la firma del tenedor. pagador. editor. caj�n..pdf
Un endoso es la firma del tenedor. pagador. editor. caj�n..pdfambikacollection1084
 
Un entusiasta estudiante de posgrado en Carleton cuenta gansos en lo.pdf
Un entusiasta estudiante de posgrado en Carleton cuenta gansos en lo.pdfUn entusiasta estudiante de posgrado en Carleton cuenta gansos en lo.pdf
Un entusiasta estudiante de posgrado en Carleton cuenta gansos en lo.pdfambikacollection1084
 
Un empleado de Liberty Mutual Insurance Co. present� una demanda ale.pdf
Un empleado de Liberty Mutual Insurance Co. present� una demanda ale.pdfUn empleado de Liberty Mutual Insurance Co. present� una demanda ale.pdf
Un empleado de Liberty Mutual Insurance Co. present� una demanda ale.pdfambikacollection1084
 
Un ejemplo de las habilidades de liderazgo de Shackleton en la pr�ct.pdf
Un ejemplo de las habilidades de liderazgo de Shackleton en la pr�ct.pdfUn ejemplo de las habilidades de liderazgo de Shackleton en la pr�ct.pdf
Un ejemplo de las habilidades de liderazgo de Shackleton en la pr�ct.pdfambikacollection1084
 
Un discurso a menudo diferir� de un diario porque el discurso, di.pdf
Un discurso a menudo diferir� de un diario porque el discurso, di.pdfUn discurso a menudo diferir� de un diario porque el discurso, di.pdf
Un discurso a menudo diferir� de un diario porque el discurso, di.pdfambikacollection1084
 
Un d�a en la vida�2019 Troi, la directora de proyectos de un gran .pdf
Un d�a en la vida�2019 Troi, la directora de proyectos de un gran .pdfUn d�a en la vida�2019 Troi, la directora de proyectos de un gran .pdf
Un d�a en la vida�2019 Troi, la directora de proyectos de un gran .pdfambikacollection1084
 
Trey Monson starts a merchandising business on December 1 and enters.pdf
Trey Monson starts a merchandising business on December 1 and enters.pdfTrey Monson starts a merchandising business on December 1 and enters.pdf
Trey Monson starts a merchandising business on December 1 and enters.pdfambikacollection1084
 
Trending HR Issues. Students are asked to source 2 newspapetjournal.pdf
Trending HR Issues. Students are asked to source 2 newspapetjournal.pdfTrending HR Issues. Students are asked to source 2 newspapetjournal.pdf
Trending HR Issues. Students are asked to source 2 newspapetjournal.pdfambikacollection1084
 
TP BASE DE DONN�ES.1. Quelles sont les limites des fichiers .pdf
TP BASE DE DONN�ES.1. Quelles sont les limites des fichiers .pdfTP BASE DE DONN�ES.1. Quelles sont les limites des fichiers .pdf
TP BASE DE DONN�ES.1. Quelles sont les limites des fichiers .pdfambikacollection1084
 
Trace each loop b. String[ ] arr ={ Whose, woods, these, are.pdf
Trace each loop b. String[ ] arr ={ Whose, woods, these, are.pdfTrace each loop b. String[ ] arr ={ Whose, woods, these, are.pdf
Trace each loop b. String[ ] arr ={ Whose, woods, these, are.pdfambikacollection1084
 
Trabajando individualmente o en grupos, utilice los recursos de Inte.pdf
Trabajando individualmente o en grupos, utilice los recursos de Inte.pdfTrabajando individualmente o en grupos, utilice los recursos de Inte.pdf
Trabajando individualmente o en grupos, utilice los recursos de Inte.pdfambikacollection1084
 
Topic Number of social media users before and during the COVID-19 c.pdf
Topic Number of social media users before and during the COVID-19 c.pdfTopic Number of social media users before and during the COVID-19 c.pdf
Topic Number of social media users before and during the COVID-19 c.pdfambikacollection1084
 

More from ambikacollection1084 (20)

Un grupo de investigadores est� estudiando el oper�n WOLF, que se en.pdf
Un grupo de investigadores est� estudiando el oper�n WOLF, que se en.pdfUn grupo de investigadores est� estudiando el oper�n WOLF, que se en.pdf
Un grupo de investigadores est� estudiando el oper�n WOLF, que se en.pdf
 
Un hombre de 28 a�os ten�a varias quejas. Ten�a un caso grave de aft.pdf
Un hombre de 28 a�os ten�a varias quejas. Ten�a un caso grave de aft.pdfUn hombre de 28 a�os ten�a varias quejas. Ten�a un caso grave de aft.pdf
Un hombre de 28 a�os ten�a varias quejas. Ten�a un caso grave de aft.pdf
 
Un grupo de procesos que busca combinar las caracter�sticas y vent.pdf
Un grupo de procesos que busca combinar las caracter�sticas y vent.pdfUn grupo de procesos que busca combinar las caracter�sticas y vent.pdf
Un grupo de procesos que busca combinar las caracter�sticas y vent.pdf
 
Un gobierno decide donar a perpetuidad con pagos anuales debido a un.pdf
Un gobierno decide donar a perpetuidad con pagos anuales debido a un.pdfUn gobierno decide donar a perpetuidad con pagos anuales debido a un.pdf
Un gobierno decide donar a perpetuidad con pagos anuales debido a un.pdf
 
Un estudio de caso de marca compartida Escribir un correo electr�n.pdf
Un estudio de caso de marca compartida Escribir un correo electr�n.pdfUn estudio de caso de marca compartida Escribir un correo electr�n.pdf
Un estudio de caso de marca compartida Escribir un correo electr�n.pdf
 
Un escenario Mary trabaja en el departamento de gesti�n de informaci.pdf
Un escenario Mary trabaja en el departamento de gesti�n de informaci.pdfUn escenario Mary trabaja en el departamento de gesti�n de informaci.pdf
Un escenario Mary trabaja en el departamento de gesti�n de informaci.pdf
 
un desarrollador acord� pagar la infraestructura de agua y aguas res.pdf
un desarrollador acord� pagar la infraestructura de agua y aguas res.pdfun desarrollador acord� pagar la infraestructura de agua y aguas res.pdf
un desarrollador acord� pagar la infraestructura de agua y aguas res.pdf
 
Un estudio de 2015 de hospitales, plantas de energ�a y servicios de .pdf
Un estudio de 2015 de hospitales, plantas de energ�a y servicios de .pdfUn estudio de 2015 de hospitales, plantas de energ�a y servicios de .pdf
Un estudio de 2015 de hospitales, plantas de energ�a y servicios de .pdf
 
Un endoso es la firma del tenedor. pagador. editor. caj�n..pdf
Un endoso es la firma del tenedor. pagador. editor. caj�n..pdfUn endoso es la firma del tenedor. pagador. editor. caj�n..pdf
Un endoso es la firma del tenedor. pagador. editor. caj�n..pdf
 
Un entusiasta estudiante de posgrado en Carleton cuenta gansos en lo.pdf
Un entusiasta estudiante de posgrado en Carleton cuenta gansos en lo.pdfUn entusiasta estudiante de posgrado en Carleton cuenta gansos en lo.pdf
Un entusiasta estudiante de posgrado en Carleton cuenta gansos en lo.pdf
 
Un empleado de Liberty Mutual Insurance Co. present� una demanda ale.pdf
Un empleado de Liberty Mutual Insurance Co. present� una demanda ale.pdfUn empleado de Liberty Mutual Insurance Co. present� una demanda ale.pdf
Un empleado de Liberty Mutual Insurance Co. present� una demanda ale.pdf
 
Un ejemplo de las habilidades de liderazgo de Shackleton en la pr�ct.pdf
Un ejemplo de las habilidades de liderazgo de Shackleton en la pr�ct.pdfUn ejemplo de las habilidades de liderazgo de Shackleton en la pr�ct.pdf
Un ejemplo de las habilidades de liderazgo de Shackleton en la pr�ct.pdf
 
Un discurso a menudo diferir� de un diario porque el discurso, di.pdf
Un discurso a menudo diferir� de un diario porque el discurso, di.pdfUn discurso a menudo diferir� de un diario porque el discurso, di.pdf
Un discurso a menudo diferir� de un diario porque el discurso, di.pdf
 
Un d�a en la vida�2019 Troi, la directora de proyectos de un gran .pdf
Un d�a en la vida�2019 Troi, la directora de proyectos de un gran .pdfUn d�a en la vida�2019 Troi, la directora de proyectos de un gran .pdf
Un d�a en la vida�2019 Troi, la directora de proyectos de un gran .pdf
 
Trey Monson starts a merchandising business on December 1 and enters.pdf
Trey Monson starts a merchandising business on December 1 and enters.pdfTrey Monson starts a merchandising business on December 1 and enters.pdf
Trey Monson starts a merchandising business on December 1 and enters.pdf
 
Trending HR Issues. Students are asked to source 2 newspapetjournal.pdf
Trending HR Issues. Students are asked to source 2 newspapetjournal.pdfTrending HR Issues. Students are asked to source 2 newspapetjournal.pdf
Trending HR Issues. Students are asked to source 2 newspapetjournal.pdf
 
TP BASE DE DONN�ES.1. Quelles sont les limites des fichiers .pdf
TP BASE DE DONN�ES.1. Quelles sont les limites des fichiers .pdfTP BASE DE DONN�ES.1. Quelles sont les limites des fichiers .pdf
TP BASE DE DONN�ES.1. Quelles sont les limites des fichiers .pdf
 
Trace each loop b. String[ ] arr ={ Whose, woods, these, are.pdf
Trace each loop b. String[ ] arr ={ Whose, woods, these, are.pdfTrace each loop b. String[ ] arr ={ Whose, woods, these, are.pdf
Trace each loop b. String[ ] arr ={ Whose, woods, these, are.pdf
 
Trabajando individualmente o en grupos, utilice los recursos de Inte.pdf
Trabajando individualmente o en grupos, utilice los recursos de Inte.pdfTrabajando individualmente o en grupos, utilice los recursos de Inte.pdf
Trabajando individualmente o en grupos, utilice los recursos de Inte.pdf
 
Topic Number of social media users before and during the COVID-19 c.pdf
Topic Number of social media users before and during the COVID-19 c.pdfTopic Number of social media users before and during the COVID-19 c.pdf
Topic Number of social media users before and during the COVID-19 c.pdf
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf

  • 1. Topic: Use stacks to solve Maze. DO NOT USE RECURSION. And do not use hashmaps Position.java public class Position { /*************************** * Attributes ****************************/ private int row; private int column; /*************************** * Constructor * * @param row * @param column ***************************/ public Position(int row, int column) { this.row = row; this.column = column; } /************************** * Checks two positions for equality. Two positions are equal if the have the * same row and column numbers. *************************/ public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Position)) { return false; } Position otherPosition = (Position) obj; return (otherPosition.row == row && otherPosition.column == column); } public String toString() { return "row:" + row + " column:" + column;
  • 2. } /************************** * Getter and Setter methods * * @return */ public int getRow() { return row; } public int getColumn() { return column; } } Maze.java public class Maze { /** * Two dimensional array to represent a maze */ private final char[][] maze; private final Position start, end; /** * Constructor initializing the maze array * * @param maze */ public Maze(char[][] maze, Position start, Position end) { this.maze = maze; if (validPosition(start)) { this.start = start; } else { throw new PositionNotValidException("The start position is valid for the maze: " + start); } if (validPosition(end)) { this.end = end; } else { throw new PositionNotValidException("The stop position is valid for the maze: " + end);
  • 3. } } /** * Returns the start position object. * * @return The start position. */ public Position getStart() { return start; } /** * Returns the stop position object. * * @return */ public Position getEnd() { return end; } /** * Returns the number of rows the maze has. * * @return The number of rows. */ public int numRows() { return maze.length; } /** * Returns the number of columns the row of the maze has. * * @param row The row to get the length of. * @return The length of the row in the maze. */ public int numCols(int row) { return maze[row].length; } /**
  • 4. * Tests if row and column are valid within the two dimensional array. Will * return true iff row is between 0 and maze.length-1 and column is between 0 * and maze[row].length - 1. * * @param row Represents the array to retrieve from maze. * @param col Represents the character to retrieve from the array at maze[row]. * @return True iff the row and column are valid indices of maze otherwise * false. */ public boolean validPosition(int row, int col) { if (row >= 0 && row < maze.length) { if (col >= 0 && col < maze[row].length) { return true; } } return false; } /** * Tests if the row and column stored in pos are valid. Drops to the * validPosition(int row, int col) method. * * @param pos The position to test. * @return True iff pos is valid inside the maze otherwise false. */ public boolean validPosition(Position pos) { return validPosition(pos.getRow(), pos.getColumn()); } /** * Returns the character at pos. * * @param pos The position to retrieve the character at. * @return The character at maze[pos.row][pos.column] * @throws PositionNotValidException if the position is now within the maze. */ public char getAt(Position pos) { if (validPosition(pos)) {
  • 5. return maze[pos.getRow()][pos.getColumn()]; } else { String msg = String.format("The position given is not valid: %s", pos.toString()); throw new PositionNotValidException(msg); } } /** * Retrieves the character at maze[row][column]. * * @param row The row to retrieve the character from. * @param column The column to retrieve the character from. * @return The character at position row, column * @throws PositionNotValidException if the row or column are not within bounds. */ public char getAt(int row, int column) { if (validPosition(row, column)) { return maze[row][column]; } else { String msg = String.format("The row and column given is not valid: row %d col %d", row, column); throw new PositionNotValidException(msg); } } /** * Sets a character at a specified position. * * @param pos The position to set the character at. * @param c The character to set at position. * @throws PositionNotValidException if the position passed in is not valid * within the maze. */ public void setAt(Position pos, char c) { if (validPosition(pos)) { setAt(pos.getRow(), pos.getColumn(), c); } else { String msg = String.format("The position given is not valid: %s", pos.toString());
  • 6. throw new PositionNotValidException(msg); } } /** * Sets a character at a specified row and column. * * @param pos The position to set the character at. * @param c The character to set at position. * @throws PositionNotValidException if the position passed in is not valid * within the maze. */ public void setAt(int row, int column, char c) { if (validPosition(row, column)) { maze[row][column] = c; } else { String msg = String.format("The row and column given is not valid: row %d col %d", row, column); throw new PositionNotValidException(msg); } } /*** METHODS NOT NEEDED TO HELP SOLVE THE PROBLEM. ****/ /*** YOU DO NOT NEED TO USE THESE METHODS AS THEY ****/ /*** ARE USED IN THE MAIN CLASS. ****/ public Maze clone() { char clone[][] = new char[maze.length][]; for (int r = 0; r < maze.length; r++) { clone[r] = new char[maze[r].length]; for (int c = 0; c < maze[r].length; c++) { clone[r][c] = maze[r][c]; } } return new Maze(clone, start, end); } public String toString() { StringBuffer sb = new StringBuffer(); for (int r = 0; r < maze.length; r++) {
  • 7. sb.append(maze[r]); sb.append("n"); } return sb.toString(); } } MazeSolver.java - ONE THAT I NEED A HELP WITH!! import java.util.Stack; /** * Notes: * * The start and end position are contained within the maze object. Use the * getStart() and getEnd() methods. * */ public class MazeSolver { /** * You need to implement this method * * @param maze: The maze to be solved. * @return An array of Position which stores a solution to the maze. If a * solution is not found a null value should be returned. */ public static Position[] solve(Maze maze) { return null; } } Consider a maze made up of rectangular array of squares, such as the following one: rigure 1-- A sampie maze The " X " blocks represent a blocked square and form the walls of the maze. Let us consider mazes that have only one entrance and one exit, as in our example. Beginning at the entrance at the top left side of the maze, find a path to the exit at the bottom right side. You can move only up, down, left, or right. Square is either clear or blocked by an X character. Let a two- dimensional array represent the maze. Use a stack data structure to find a path through the maze. Some mazes might have more than one successful path, while others might have no path. Hints: - The primary consideration is that if you reach a dead end, you need to be able to backtrack along the path to the point where you can try a different path. The stack data structure makes it possible to store the current path and backtrack if necessary. Every clear position visited in the current
  • 8. path is pushed to the stack and if a dead end is reached, the previous position is popped from the stack to backtrack. You need to have a loop that begins with the start position and pushes it into the stack then moves to a neighboring cell until either the goal position is reached, or the stack becomes empty. - Make sure to mark each clear array cell you move to as visited to avoid checking it again and getting stuck in an infinite loop. For example, each array cell can have three different values: " " for blocked, "V" for visited, and " "for clear. - A dead end is an array cell whose all neighbors are either blocked or already visited. There are four files you should pay attention to: - Position.java: a class to store the position of an array cell. It has two attributes: row and column along with their accessor and mutator methods. It also has an equal's method that checks for equality of two Position objects. - Maze.java: a class to store a maze. It has 3 attributes: a two-dimensional character array which represents the maze, a Position object to represent the start location, and another Position object to represent the stop location. - MazeSolver: This class contains one static method, solve. It accepts a maze and returns an array of Positions that is used to traverse the maze if the maze is solvable. If the maze is not solvable then an empty array is returned. - Keep in mind that stacks store objects in reverse order so be sure to return the position array in the correct order. - Tester: a sample driver class which calls the traverse method on a maze in either the SolvableMaze, UnsolvableMaze, or HugeSolvableMaze files. These should be at the root of the project folder. You only need to implement the solve method in the MazeSolver.java class. This method receives the maze to solve as a parameter and returns an array of Position objects which stores a solution to the maze if such solution exists; otherwise, it returns an empty array. Note: There might be more than one possible solution to a maze, depending on the ordering in which the neighboring cells are visited at each location. You can do whatever order you want if the maze is solved. For instance, First move left, if the left neighbor is not clear, then move right, if the right neighbor is not clear, then move up, if it is not clear, then move down. You may create any additional helper methods to aid you. For instance, you may make a method to convert the stack to a necessary array. Just remember, when you grab the information from a stack you are getting in the reverse order you push them. You must solve the problem using a Stack. You may use the built-in stack library but use of any other data structure is prohibited apart from constructing the final Position array result. Recursion is also not allowed. What you need to turn in: You need to submit the MazeSolver.java file containing your implementation of the solve method. Additional Notes and Helpful Hints First hint I have is to not be afraid of creating additional variables to store information. For instance, you must move up, down, left, and right (or north, south, west, and east). Creating Position objects to represent these movements is perfectly
  • 9. acceptable. You will also want to create an object that is the walker of the maze. This walker keeps the current position in the maze. Other than push, pop, and peek on the Stack class, isEmpty is also a useful method. The maze class contains a bunch of methods that is meant to help you. Read what the methods do and decide which ones you want to use for your solution. Read the code given to you FIRST before starting to write your code so you can utilize it. It is there to make your life easier, not harder. Try to translate what you want to do in terms of the stack operations. For instance, if you find yourself at a dead end then you want to move back to a previous position. This means you will need to first pop the top position, which contains the spot located at the dead end, then peek to see where you need to be. Your stack should be declared and initialized as such: Stack> _ Give it a name _ = new Stack < Position =(); where you can name it whatever you want. Moving in a two-dimensional array requires the following math: