package ahao.alg;
import java.util.List;
import java.util.Stack;
public class SolveMap {
int map[][];
Stack path = new Stack();
List> paths = new Stack>();
public SolveMap(int map[][]) {
this.map = map;
}
public static void main(String[] args) {
int map[][] = { { 1, 1, 1, 1, 1 }, { 1, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 1, 1, 1, 1 } };
SolveMap solveMap = new SolveMap(map);
solveMap.getPath(1, 1, 3, 1);
}
public void getPath(int x, int y, int aimx, int aimy) {
int i, j, dire;
map[x][y] = 1;
path.add(new Node(x, y, -1));
while (!path.isEmpty()) {
i = path.lastElement().x;
j = path.lastElement().y;
dire = path.lastElement().dire;
if (i == aimx && j == aimy) {
paths.add(path);
System.out.println("第" + paths.size() + "条路径为:(需要走"
+ (path.size() - 1) + "步)");
for (int k = 0; k < path.size(); k++) {
System.out.println("\t(" + path.get(k).x + ","
+ path.get(k).y + ")");
}
map[aimx][aimy] = 0;
path.pop();
i = path.lastElement().x;
j = path.lastElement().y;
dire = path.lastElement().dire;
}
int find = 0;
while (dire < 4 && find == 0) {
dire++;
switch (dire) {
case 0:
i = path.lastElement().x - 1;
j = path.lastElement().y;
break;
case 1:
i = path.lastElement().x;
j = path.lastElement().y + 1;
break;
case 2:
i = path.lastElement().x + 1;
j = path.lastElement().y;
break;
case 3:
i = path.lastElement().x;
j = path.lastElement().y - 1;
break;
}
if (map[i][j] == 0) {
find = 1;
}
}
if (find == 1) {
path.lastElement().dire = dire;
path.add(new Node(i, j, -1));
map[i][j] = 1;
} else {
Node node = path.lastElement();
map[node.x][node.y] = 0;
path.pop();
}
}
if (paths.size() == 0)
System.out.println("没有相关路径!");
else {
System.out.println("共有" + paths.size() + "条路径");
}
}
}
class Node {
int x, y, dire;
public Node() {
}
public Node(int x, int y, int dire) {
super();
this.x = x;
this.y = y;
this.dire = dire;
}
}