Loops - itk.ilstu.edu

An application of using Stacks
Going through a Maze
Try This
Principle:
Remember
the return
path in case
we have to go
back
7/28/2017
IT 179
1
Play Maze
public class Maze {
/**
* Test if p is a valid move, i.e., a space ' ' in m[p.x][p.y].
* @param m char[][], a 2-dimensional char array.
* @param p Point, a position
* @return
*/
private static boolean validMove(char[][] m, Point p) {
return
p.x >= 0 && p.x < m.length &&
p.y >= 0 && p.y < m[0].length &&
m[p.x][p.y] == ' ';
}
...
...
}
7/28/2017
IT 179
2
Play Maze
public class Maze {
...
/**
* Try to find next move from current position
*/
static Point nextMove(char[][] m, Point current) {
Point next;
next = new Point(current.x,current.y+1); // try
if (validMove(m,next)) return next;
next = new Point(current.x+1,current.y); // try
if (validMove(m,next)) return next;
next = new Point(current.x,current.y-1); // try
if (validMove(m,next)) return next;
next = new Point(current.x-1,current.y); // try
if (validMove(m,next)) return next;
return null;
}
7/28/2017
IT 179
east
south
west
north
3
/* Solving a maze: put '.' to the exit path, 'X' a failed try.
*/
public static LStack<Point> solve(char[][] m, Point start, Point exit) {
LStack<Point> path = new LStack<Point>();
Point next, current = new Point(start);
while (current.x != exit.x || current.y != exit.y) {
next = nextMove(m, current); // try to find next move
if (next == null) { // no possible next move
if (path.empty())
// if empty, no way to return;
return null; // i.e., no solution
m[current.x][current.y] = 'X'; // don't come back again
current = path.pop();
} else {
m[current.x][current.y] = '.';
path.push(current);
current = next;
}
}
m[current.x][current.y] = '.';
path.push(current);
return path;
}
7/28/2017
IT 179
4