Presentation is loading. Please wait.

Presentation is loading. Please wait.

An application of using Stacks

Similar presentations


Presentation on theme: "An application of using Stacks"— Presentation transcript:

1 An application of using Stacks
Going through a Maze Try This Principle: Remember the return path in case we have to go back 11/27/2018 IT 179

2 Play Maze public class Maze {
/** * Test if p is a valid move, i.e., a space ' ' in m[p.x][p.y]. m char[][], a 2-dimensional char array. p Point, a position */ 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] == ' '; } ... 11/27/2018 IT 179

3 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 east if (validMove(m,next)) return next; next = new Point(current.x+1,current.y); // try south next = new Point(current.x,current.y-1); // try west next = new Point(current.x-1,current.y); // try north return null; } 11/27/2018 IT 179

4 /* 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; } return path; 11/27/2018 IT 179


Download ppt "An application of using Stacks"

Similar presentations


Ads by Google