如下是迷宫问题的求解思路,可以粘贴在Eclipse下执行,请各位同仁指正。
import java.util.Stack;
public class MazePath {
int maze[][] = new int[10][10];
public MazePath(){
maze[1][3] = 1; maze[1][7] = 1;
maze[2][3] = 1; maze[2][7] = 1;
maze[3][5] = 1; maze[3][6] = 1;
maze[4][2] = 1; maze[4][3] = 1; maze[4][4] = 1;
maze[5][4] = 1;
maze[6][2] = 1; maze[6][6] = 1;
maze[7][2] = 1; maze[7][3] = 1; maze[7][4] = 1; maze[7][6] = 1; maze[7][7] = 1;
maze[8][1] = 1;
for (int j = 0; j < 10; j++) {
maze[0][j] = 1;
maze[9][j] = 1;
maze[j][0] = 1;
maze[j][9] = 1;
}
}
public void mazePath () {
Stack stack = new Stack();
int i = 1, j = 1;
stack.add(new PosEle(i, j, 1));
j++;
PosEle current;
while (!stack.isEmpty()) {
if ((i == 8 && j == 8)) {
printStack(stack);
maze[i][j] = -1;
}
if (maze[i][j] == 0) {
stack.add(new PosEle(i, j, 1));
maze[i][j] = -1;
j++;
} else {
do {
current = (PosEle) stack.pop();
} while (current.dir == 4 && !stack.isEmpty());
i = current.i;
j = current.j;
if (current.dir < 4) {
if (current.dir == 1) {
i++;
} else if (current.dir == 2) {
j--;
} else if (current.dir == 3) {
i--;
}
current.dir++;
stack.add(current);
}
}
}
}
void printStack(Stack stack) {
System.out.println("Print one path");
for (int i = 0; i < stack.size(); i++) {
System.out.println(stack.get(i));
}
}
public static void main(String[] args) {
new MazePath().mazePath();
}
}
class PosEle {
int i, j;
int dir = 0;
PosEle (int i, int j, int dir) {
this.i = i;
this.j = j;
this.dir = dir;
}
public String toString() {
return i + ", " + j;
}
}