I'm trying to traverse a maze using recursion for class. I was provided the template and just need to input the the process of traversing the maze; I am not allowed to alter the code in any way besides what is being plugged in after this:
public boolean mazeTraversal (char maze2[][], int x, int y)
I have been having a really hard time with this and don't know what I am missing. I am still and ultra noob when it comes to Java and programming in general. Any hints would be greatly appreciated.
// Exercise 18.20 Solution: Maze.java
//Program traverses a maze.
import java.util.Scanner;
package maze;
public class Maze {
public static void main( String args[] )
{
}
/**
* @param args the command line arguments
*/
static final int DOWN = 0;
static final int RIGHT = 1;
static final int UP = 2;
static final int LEFT = 3;
static final int X_START = 2;
static final int Y_START = 0;
static final int move = 0;
static char maze [][] =
{ { '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' },
{ '#', '.', '.', '.', '#', '.', '.', '.', '.', '.', '.', '#' },
{ 'S', '.', '#', '.', '#', '.', '#', '#', '#', '#', '.', '#' },
{ '#', '#', '#', '.', '#', '.', '.', '.', '.', '#', '.', '#' },
{ '#', '.', '.', '.', '.', '#', '#', '#', '.', '#', '.', 'F' },
{ '#', '#', '#', '#', '.', '#', '.', '#', '.', '#', '.', '#' },
{ '#', '.', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#' },
{ '#', '#', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#' },
{ '#', '.', '.', '.', '.', '.', '.', '.', '.', '#', '.', '#' },
{ '#', '#', '#', '#', '#', '#', '.', '#', '#', '#', '.', '#' },
{ '#', '.', '.', '.', '.', '.', '.', '#', '.', '.', '.', '#' },
{ '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' } };
static Scanner scanner = new Scanner (System.in);
//method calls mazeTraversal with correct starting point and direction
public void traverse ()
{
boolean result = mazeTraversal (maze, X_START, Y_START);
if (!result)
System.out.println ("Maze has no solution.");
} //end method traverse
//traverse maze recursively
public boolean mazeTraversal (char maze2[][], int x, int y)
{
// TO BE COMPLETED
//check for boundaries
if (x < 0 || y < 0 || x >= maze.length || y >= maze[0].length)
return false;
//base case - did I reach finish?
if(maze [x][y] == 'F')
return true;
//check if Valid point
if (maze [x][y] != '.' || maze[x][y] != 'S')
// hit a wall, not valid
return false;
//must be on a path, may be the right path
//breadcrumb
maze [x][y] = '.';
//up
if (mazeTraversal (x+1,y))
{
maze [x][y]= '#';
return true;
}
if (mazeTraversal (x,y+1))
{
maze [x][y] = '#';
return true;
}
// can't go any further
return false;
}
}
//draw maze
public void printMaze()
{
// for each space in maze
for ( int row = 0; row < maze.length; row++)
{
for (int column = 0; column < maze [row].length; column++)
{
if (maze [x][y] == '0')
System.out.print (".");
else
System.out.print (" " + maze [x][y]);
}
System.out.println();
}
System.out.println();
}
}
Aucun commentaire:
Enregistrer un commentaire