1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import java.util.Stack;
public class Solution { public final int M = 6; public final int N = 8; public int[][] maze = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 1, 1, 1, 0, 1, 1, 1, 1}, {1, 1, 0, 1, 0, 1, 1, 1, 1, 1}, {1, 0, 1, 0, 0, 0, 0, 0, 1, 1}, {1, 0, 1, 1, 1, 0, 1, 1, 1, 1}, {1, 1, 0, 0, 1, 1, 0, 0, 0, 1}, {1, 0, 1, 1, 0, 0, 1, 1, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} }; public Direction directions[] = { new Direction(0, 1), new Direction(1, 1), new Direction(1, 0), new Direction(1, -1), new Direction(0, -1), new Direction(-1, -1), new Direction(-1, 0), new Direction(-1, 1) };
public boolean isExit() { Stack s = new Stack(); int x, y, d; int i, j; s.push( new Item(1, 1, 0)); while (!s.empty()) { Item item = (Item) s.pop(); x = item.x; y = item.y; d = item.d; while (d < 8) { i = x + directions[d].x; j = y + directions[d].y; if (maze[i][j] == 0) { s.push(new Item(x, y, d)); x = i; y = j; maze[x][y] = 3; if (x == M && y == N) return true; else { d = 0; } } else { d++; } }
} return false;
}
}
class Direction { int x, y;
public Direction(int x, int y) { this.x = x; this.y = y; } }
class Item { int x, y, d;
public Item(int x, int y, int d) { this.x = x; this.y = y; this.d = d; } }
JAVA
|