如下图为一个8*8的矩阵A表示的迷宫,其中0为路,1为墙壁,以矩阵A[0][0]作为起点,通过使用数据结构栈来设计算法,在矩阵中进行迷宫探索,直至找到迷宫出口(出口默认在最下面一行),并打印出正确的走出迷宫的行走路径,即打印路径每个点的坐标,如(0,0);(0,1);(0,2),(1,2)......
public class Node {
int y;
int x;
Node next;
public Node() {
}
public Node(int y, int x) {
this.y = y;
this.x = x;
}
@Override
public String toString() {
return "(" +
(y-1) +
", " + (x-1) +
")";
}
}
public class Stack {
Node base;
Node top ;
public void push(Node node){
Node temp = new Node();
temp.x = node.x;
temp.y = node.y;
temp.next = top;
top = temp;
}
public boolean isEmpty(){
return base == top;
}
public Node peek(){
return top;
}
public Node pop() {
if (this.isEmpty()) {
System.out.println("退栈失败,栈为空!");
return null;
}
Node temp = new Node();
temp = top;
top = top.next;
return temp;
}
}
public class MazeProblem {
static Stack stack = new Stack();
static Stack tempStack = new Stack();
static int[][] modifiedMap;
static int[][] map;
public static void runMaze(int startY, int startX, int endY, int endX) {
modifiedMap = new int[map.length + 2][map[0].length + 2];
for (int i = 0; i < modifiedMap.length; i++) {
for (int j = 0; j < modifiedMap[0].length; j++) {
if (j == 0 || j == modifiedMap[0].length - 1 || i == 0 || i == modifiedMap.length - 1) {
modifiedMap[i][j] = 1;
} else if (i != modifiedMap.length - 1 && j != modifiedMap[0].length - 1) {
modifiedMap[i][j] = map[i - 1][j - 1];
}
}
}
int[] y = {-1, 0, 1, 0};
int[] x = {0, 1, 0, -1};
stack.push(new Node(startY + 1, startX + 1));
modifiedMap[startY + 1][startX + 1] = 2;
while (!stack.isEmpty()) {
Node cur = stack.peek();
if (cur.y == endY + 1 && cur.x == endX + 1) {
printResult();
System.out.println("-----------------");
break;
}
int i;
for (i = 0; i < 4; i++) {
int row = cur.y + y[i];
int column = cur.x + x[i];
if (modifiedMap[row][column] == 0) {
stack.push(new Node(row, column));
modifiedMap[row][column] = 2;
break;
}
}
if (i == 4) {
cur = stack.pop();
modifiedMap[cur.y][cur.x] = -1;
}
}
}
public static void show() {
while (stack.top != stack.base) {
tempStack.push(stack.pop());
}
while (tempStack.top != tempStack.base) {
System.out.println(tempStack.pop());
}
}
public static void printResult() {
for (int i = 1; i < modifiedMap.length - 1; i++) {
for (int j = 1; j < modifiedMap[i].length - 1; j++) {
if (modifiedMap[i][j + 1] == -1) {
System.out.print(modifiedMap[i][j] + " ");
} else {
System.out.print(modifiedMap[i][j] + " ");
}
}
System.out.println();
}
}
}
public class TestMaze {
public static void main(String[] args) {
MazeProblem.map = new int[][]{
{0, 0, 0, 1, 1, 1, 1, 1},
{1, 1, 0, 1, 1, 1, 1, 1},
{1, 1, 0, 1, 0, 0, 0, 1},
{1, 1, 0, 0, 0, 1, 1, 1},
{1, 0, 0, 1, 0, 1, 1, 1},
{1, 0, 1, 1, 0, 0, 0, 1},
{1, 0, 0, 1, 1, 1, 0, 1},
{1, 1, 0, 1, 1, 1, 1, 1},
};
MazeProblem.runMaze(0, 0, 7, 2);
MazeProblem.show();
}
}
没有特别幸运,那么请先特别努力,别因为懒惰而失败,还矫情地将原因归于自己倒霉。