任务:随机生成一个迷宫图,0和1分别表示迷宫中的通路和障碍,设计一个程序,对任意设定的迷宫,求出一条从入口到出口的通路,或得出没有通路的结论。
要求:
(1)编写一个求解迷宫的非递归程序,并将求得的通路以三元组(i,j,d)的形式输出,其中: i,j指示迷宫中的一个坐标,d表示走到下一坐标的方向;
(2)编写递归形式的算法,求得迷宫中所有可能的通路;
迷宫问题的核心算法应该是回溯法,也可以说迷宫问题很好的体现了回溯法,运用深度优先搜索对所有节点以及其子节点进行遍历并标记每一步,如果没有解就返回上一个节点并撤销标记。
public class threeTuple {
int i;
int j;
int k;
threeTuple(int i, int j, int k){
this.i = i;
this.j = j;
this.k = k;
}
public int getI(){
return i;
}
public int getJ(){
return j;
}
public int getK(){
return k;
}
}
public class Maze2 {
private int[][] array = {
{0, 0, 1, 1, 1, 1, 1, 0},
{0, 1, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 0, 1},
{0, 1, 1, 1, 0, 1, 0, 1},
{0, 0, 0, 1, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 1, 0, 1},
{0, 1, 1, 1, 1, 0, 0, 1},
{0, 0, 0, 0, 0, 1, 0, 1},
{1, 1, 0, 1, 0, 0, 0, 0}
};
private int maxLine = 8;
private int maxRow = 9;
static int count = 0;
static int step = 0;
int tail = 0;
static threeTuple [] sz = new threeTuple[100];
/* 0表示向左
* 1表示向右
* 2表示向下
* 3表示向上
* */
private void findPath(int i, int j) {
//到达右下角出口
if (i == maxRow - 1 && j == maxLine - 1) {
//array[i][j] = 3;
print();
count++;
return;
}
//向右走
if (Move(i, j, i, j + 1)) {
threeTuple sy = new threeTuple(i,j,1);
sz[tail ++] = sy;
array[i][j] = 3;
findPath(i, j + 1);
array[i][j] = 0;
tail --;
}
//向左走
if (Move(i, j, i, j - 1)) {
threeTuple sy = new threeTuple(i,j,0);
sz[tail ++] = sy;
array[i][j] = 3;
findPath(i, j - 1);
array[i][j] = 0;
tail --;
}
//向下走
if (Move(i, j, i + 1, j)) {
threeTuple sy = new threeTuple(i,j,2);
sz[tail ++] = sy;
array[i][j] = 3;
findPath(i + 1, j);
array[i][j] = 0;
tail --;
}
//向上走
if (Move(i, j, i - 1, j)) {
threeTuple sy = new threeTuple(i,j,3);
sz[tail ++] = sy;
array[i][j] = 3;
findPath(i - 1, j);
array[i][j] = 0;
tail --;
}
}
private boolean Move(int i, int j, int I, int J) {
if (I < 0 || J < 0 || I >= maxRow || J >= maxLine) {
return false;
}
if (array[I][J] == 1) {
return false;
}
if (array[I][J] == 3) {
return false;
}
return true;
}
private void print() {
for (int i = 0; i < maxRow; i++) {
for (int j = 0; j < maxLine; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
for(int i=0; i<tail; i++)
System.out.println("("+sz[i].getI()+","+sz[i].getJ()+","+sz[i].getK()+")");
System.out.println("一共"+(tail+1)+"步");
System.out.println("**********************************");
}
public static void main(String[] args) {
Maze2 mz = new Maze2();
mz.findPath(0, 0);
System.out.println("一共"+count+"个解");
System.out.println();
}
}