Question

JAVA QUESTION!!! please help! The following codes are a Maze program. There are TWO traversable paths...

JAVA QUESTION!!! please help!

The following codes are a Maze program. There are TWO traversable paths possible in this maze. The program uses recursion. Can someone please explain to me why the program will pick one path if multiple traversable paths are available? Why does the program choose one path over a different path? (I believe it has something to do with the recursion terminating when a solution is found but I'm not sure.)

Thank you!!!!

The codes:

public class Maze
{
   private final int TRIED = 3;
   private final int PATH = 7;

   private int[][] grid = { {1,1,1,0,1,1,0,0,0,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1,0,0,1},
{0,0,0,0,1,0,1,0,1,0,1,0,0},
{1,1,1,0,1,1,1,0,1,0,1,1,1},
{1,0,1,0,0,0,0,1,1,1,0,0,1},
{1,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,1,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1} };

   //-----------------------------------------------------------------
   // Attempts to recursively traverse the maze. Inserts special
   // characters indicating locations that have been tried and that
   // eventually become part of the solution.
   //-----------------------------------------------------------------
   public boolean traverse(int row, int column)
   {
boolean done = false;

if (valid(row, column))
{
   grid[row][column] = TRIED; // this cell has been tried

   if (row == grid.length-1 && column == grid[0].length-1)
done = true; // the maze is solved
   else
   {
done = traverse(row+1, column); // down
if (!done)
   done = traverse(row, column+1); // right
if (!done)
   done = traverse(row-1, column); // up
if (!done)
   done = traverse(row, column-1); // left
   }

   if (done) // this location is part of the final path
grid[row][column] = PATH;
}

return done;
   }
  
   //-----------------------------------------------------------------
   // Determines if a specific location is valid.
   //-----------------------------------------------------------------
   private boolean valid(int row, int column)
   {
boolean result = false;

// check if cell is in the bounds of the matrix
if (row >= 0 && row < grid.length &&
column >= 0 && column < grid[row].length)

   // check if cell is not blocked and not previously tried
   if (grid[row][column] == 1)
result = true;

return result;
   }

   //-----------------------------------------------------------------
   // Returns the maze as a string.
   //-----------------------------------------------------------------
   public String toString()
   {
String result = "\n";

for (int row=0; row < grid.length; row++)
{
   for (int column=0; column < grid[row].length; column++)
result += grid[row][column] + "";
   result += "\n";
}

return result;
   }
}

---------------------------end of first code-------------------------------

public class MazeSearch
{
   //-----------------------------------------------------------------
   // Creates a new maze, prints its original form, attempts to
   // solve it, and prints out its final form.
   //-----------------------------------------------------------------
   public static void main(String[] args)
   {
Maze labyrinth = new Maze();

System.out.println(labyrinth);

if (labyrinth.traverse(0, 0))
   System.out.println("The maze was successfully traversed!");
else
   System.out.println("There is no possible path.");

System.out.println(labyrinth);
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1. This program uses recusrion to find the traversible path. Lets have a look into the code

done = traverse(row+1, column); // down
if (!done)
   done = traverse(row, column+1); // right
if (!done)
   done = traverse(row-1, column); // up
if (!done)
   done = traverse(row, column-1); // left

As per the code, it will first check whether a DOWN move is valid or not. If its valid, it will skip all others and will move DOWN. If it is not, it will try RIGHT move. If RIGHT move is not valid, then it tries UP and finally LEFT if UP is an invalid move. If you observe carefully, as soon as it finds a valid path, it simply ignores all other directions and continues with that path.

Now, assume that continuing in a current path, if it does not find anymore valid moves, then it will backtract till the point where multiple paths are available and then continue with the other possible direction.

if (row == grid.length-1 && column == grid[0].length-1)
done = true; // the maze is solved

This above lines of code check if the maze is already solved or not, if it already solved, then it does not check for any other alternative paths and simply return true (meaning that a path is found).

Add a comment
Know the answer?
Add Answer to:
JAVA QUESTION!!! please help! The following codes are a Maze program. There are TWO traversable paths...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Maze Solving with Stacks Problem Statement Consider a maze made up of rectangular array of squares,...

    Maze Solving with Stacks Problem Statement Consider a maze made up of rectangular array of squares, such as the following one: X X X X X X X X X X X X X           X            X X X X    X X X           X               X     X X X     X X    X    X     X     X X X         X          X             X X X     X X X X X                X X X X X X X X X X X X X Figure...

  • This is for Java. Create ONE method/function that will return an array containing the row and...

    This is for Java. Create ONE method/function that will return an array containing the row and column of the largest integer i the 2D array. If the largest number is located on row 2, column 1, the method needs to return row 2 and column one. Do not use more than one method. Use the code below as the main. Please comment any changes. in java Given the main, create a method that RETURNS the largest number found in the...

  • Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections;...

    Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections; class Grid { private boolean bombGrid[][]; private int countGrid[][]; private int numRows; private int numColumns; private int numBombs; public Grid() { this(10, 10, 25); }    public Grid(int rows, int columns) { this(rows, columns, 25); }    public Grid(int rows, int columns, int numBombs) { this.numRows = rows; this.numColumns = columns; this.numBombs = numBombs; createBombGrid(); createCountGrid(); }    public int getNumRows() { return numRows;...

  • JAVA Only Help on the sections that say Student provide code. The student Provide code has...

    JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe {     private final int BOARDSIZE = 3; // size of the board     private enum Status { WIN, DRAW, CONTINUE }; // game states     private char[][] board; // board representation     private boolean firstPlayer; // whether it's player 1's move     private boolean gameOver; // whether...

  • Please help to make the program working. Can not compile. import java.io.*; import java .util.*; public...

    Please help to make the program working. Can not compile. import java.io.*; import java .util.*; public class Puzzlee {                 static int NN = 9; // Grid Size // sample input static int myGrid[][] = {                                                                                                                                                                                                                                                                                {0,0,0,1,0,5,0,6,8},                                                                                                                 {0,0,0,0,0,0,7,0,1},                                                                                                                 {9,0,1,0,0,0,0,3,0},                                                                                                                 {0,0,7,0,2,6,0,0,0},                                                                                                                 {5,0,0,0,0,0,0,0,3},                                                                                                                 {0,0,0,8,7,0,4,0,0},                                                                                                                 {0,3,0,0,0,0,8,0,5},                                                                                                                 {1,0,5,0,0,0,0,0,0},                                                                                                                 {7,9,0,4,0,1,0,0,0}                                                                                                 };    static class myCell {                 int myRow, myColumn;                 public myCell(int myRow, int myColumn)                 {                                 super();                                ...

  • import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private...

    import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private ArrayList<String> words; private HashSet<String> foundWords = new HashSet<String>(); public FindWordInMaze(char[][] grid) { this.grid = grid; this.words = new ArrayList<>();    // add dictionary words words.add("START"); words.add("NOTE"); words.add("SAND"); words.add("STONED");    Collections.sort(words); } public void findWords() { for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[i].length; j++) { findWordsFromLocation(i, j); } }    for(String w: foundWords) { System.out.println(w); } } private boolean isValidIndex(int i, int j, boolean visited[][]) { return...

  • Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static...

    Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static String solve(char[][] grid) {        // TODO        /*        * 1. Construct a graph using grid        * 2. Use BFS to find shortest path from start to finish        * 3. Return the sequence of moves to get from start to finish        */               // Hardcoded solution to toyTest        return...

  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • Instructions Write a program in Java that implements the A* algorithm to find a path from...

    Instructions Write a program in Java that implements the A* algorithm to find a path from any two given nodes. Problem Overview & Algorithm Description In a fully-observable environment where there are both pathable and blocked nodes, an agent must find a good path from their starting node to the goal node. The agent must use the A* algorithm to determine its path. For this program, you must use the Manhattan method for calculating the heuristic. Remember: your heuristic function...

  • You are going to be implementing the classic computer science simulation, Conway's Game of Life. Conway's...

    You are going to be implementing the classic computer science simulation, Conway's Game of Life. Conway's Life is played on a matrix of cells, kind of like a chess board but theoretically extending infinitely in every direction. Each individual cell in the matrix can either be alive or dead. A live cell in the matrix is shown in our simulation by printing an asterisk (*) to the screen. A dead cell is shown by leaving that area of the matrix...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT