思路:把迷宫抽象为由若干个节点组成的图,从入口S到出口E的一条路径,可以使用DFS或BFS来寻找。
(1)是否有路
(2)找到其中一条路径
(3)找到最短的路径
解决第(2)个问题
package Lesson1;
import java.util.HashSet;
import java.util.Set;
public class Maze {
// 使用二维数组存储图,.表示通路,#表示墙壁
private char data[][];// 迷宫数据
private Pos entry;// 入口
private Pos exit;// 出口
private Set solve = new HashSet();// 找到的解
class Pos {// 位置坐标
int i;
int j;
public Pos(int x, int y) {
i = x;
j = y;
}
// 重写hashCode和equals方法
public int hashCode() {
return i * 1000 + j;
}
public boolean equals(Object obj) {
if (obj instanceof Pos == false) {
return true;
}
Pos p = (Pos) obj;
return p.i == i && p.j == j;
}
}
private void getStdInput() {
String[] x = { "####B#######", "####....####", "####.####..#",
"#....#####.#", "#.#####.##.#", "#.#####.##.#", "#.##.......#",
"#.##.###.#.#", "#....###.#.#", "##.#.###.#.A", "##.###...###",
"############" };
data = new char[x.length][];
for (int i = 0; i < data.length; i++) {
data[i] = x[i].toCharArray();// 复制每一行
for (int j = 0; j < data[i].length; j++) {
if (data[i][j] == 'A') {// 记录入口
entry = new Pos(i, j);
}
if (data[i][j] == 'B') {// 记录出口
exit = new Pos(i, j);
}
}
}
}
private void show() {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
char c = data[i][j];
if (c == '.' && solve.contains(new Pos(i, j))) {
c = 'x';
}
System.out.print(c + " ");
}
System.out.println();
}
}
private boolean go(Pos cur, Set path) {// path记录已走过的位置,防止走回路
if (cur.equals(exit)) {// 走到出口
return true;
}
path.add(cur);// 标记为已走过
Pos[] t = { new Pos(cur.i, cur.j - 1), new Pos(cur.i, cur.j + 1),
new Pos(cur.i - 1, cur.j), new Pos(cur.i + 1, cur.j) };// 左右,上下相邻节点
for (int i = 0; i < t.length; i++) {
try {
if (data[t[i].i][t[i].j] != '#' && path.contains(t[i]) == false) {// 邻居节点不是墙壁(为通路),并且未走过
if (go(t[i], path)) {// 递归走邻居节点
solve.add(cur);
return true;
}
}
} catch (Exception e) {
}
}
return false;
}
private void go() {
Set path = new HashSet();
// solve = new HashSet();
go(entry, path);
}
public static void main(String[] args) {
// DFS
Maze a = new Maze();// 迷宫对象
a.getStdInput();
a.show();
a.go();// 求解A-->B的一条通路
System.out.println(".......................");
a.show();
}
}