| | |
| The Solution to the Maze Problem | page 5 of 7 |
import chn.util.*;
class ThreadTheMaze
{
private final static int MAXROW = 12;
private final static int MAXCOL = 12;
private final static char BLANK = ' ';
public void loadMaze(char[][] maze)
{
FileInput inFile = new FileInput("mazeData.txt");
for (int row = 1; row <= MAXROW; row++)
{
String line = inFile.readLine();
for (int col = 1; col <= MAXCOL; col++)
{
maze[row][col] = line.charAt(col-1);
}
}
}
public void printMaze(char[][] maze)
{
ConsoleIO console = new ConsoleIO ();
for (int row = 1; row <= MAXROW; row++)
{
for (int col = 1; col <= MAXCOL; col++)
{
System.out.print("" + maze[row][col]);
}
System.out.println();
}
System.out.println();
}
/**
* Will attempt to find a path out of the maze. A path will
* be marked with the ! marker. The method makes a copy of
* the array each time so that only the path out will be
* marked, otherwise extra ! markers will appear in the
* answer. The function is recursive.
*/
public void traceMaze(char[][] maze, int row, int col)
{
// make a local copy of maze
char[][] mazeCopy = new char[maze.length][maze[0].length];
for (int r = 0; r < mazeCopy.length; r++)
{
for (int c = 0; c < mazeCopy[0].length; c++)
{
mazeCopy[r][c] = maze[r][c];
}
}
if (1 <= row && row <= MAXROW && 1 <= col && col <= MAXCOL)
{
// boundary check, if false, a base case
if (BLANK == mazeCopy[row][col])
{
// if false, base case
mazeCopy[row][col] = '!';
if (1 == row || MAXROW == row ||
1 == col || MAXCOL == col)
{
printMaze(mazeCopy); // base case
}
else
{
traceMaze(mazeCopy, row - 1, col);
traceMaze(mazeCopy, row, col + 1);
traceMaze(mazeCopy, row + 1, col);
traceMaze(mazeCopy, row, col - 1);
}
}
}
}
public static void main(String[] args)
{
ThreadTheMaze mazeWalker = new ThreadTheMaze();
char[][] maze = new char[MAXROW + 1][MAXCOL + 1];
mazeWalker.loadMaze(maze);
mazeWalker.traceMaze(maze, 6, 6);
}
}
Here are the two solutions to starting at location (6,6):
| |
***!********
***! *****
***!** ****
***!!!* ***
*****!** ***
*****!** ***
***** ******
***** ****
**** * ****
* ** ****
* * *****
* **********
|
*** ********
*** *****
*** ** ****
*** * ***
***** ** ***
*****!** ***
*****!******
*****!!!****
**** *!****
*!!!**!!****
*!*!!!!*****
*!**********
|
It is very significant that a blank space be changed to an '!' mark before the recursive calls are made. For example, suppose we begin at location 6,6 and a blank space is encountered. If we did not change the blank to an '!' mark, the recursive call to solve the upward direction receives the location 5,6. This recursive call will eventually look back down at location 6,6 - the location where it came from. A blank space would still be there and the recursive calls would go round in circles until the computer runs out of memory.
Changing the blank space to an '!' mark is like leaving a trail of markers. When a recursive call of a neighboring cell looks back at the cell from which it came it will see a '!' mark and not a blank space.
|