迷宫问题,深度遍历解法
import java.util.HashSet;
import java.util.Set;
public class Puzzl {
private char[][] data;
private Pos entry;
private Pos exit;
private Set<Pos> solve = new HashSet<Pos>(); // 找到的解
class Pos {
int i;
int j;
public Pos(int x, int y) {
i = x;
j = y;
}
public int hashCode() {
return i * 1000 + j;
}
public boolean equals(Object x) {
if (x instanceof Pos == false)
return true;
Pos p = (Pos) x;
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<Pos> 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<Pos> path = new HashSet<Pos>();
solve = new HashSet<Pos>();
go(entry, path);
}
public static void main(String[] args) {
Puzzl a = new Puzzl();// 新建对象
a.getStdInput();// 初始化
a.show();// 展示
a.go();// 求解
System.out.println("----------------------");
a.show();
}
}
结果
# # # # B # # # # # # #
# # # # . . . . # # # #
# # # # . # # # # . . #
# . . . . # # # # # . #
# . # # # # # . # # . #
# . # # # # # . # # . #
# . # # . . . . . . . #
# . # # . # # # . # . #
# . . . . # # # . # . #
# # . # . # # # . # . A
# # . # # # . . . # # #
# # # # # # # # # # # #
----------------------
# # # # B # # # # # # #
# # # # x . . . # # # #
# # # # x # # # # . . #
# x x x x # # # # # . #
# x # # # # # . # # . #
# x # # # # # . # # . #
# x # # x x x x x x x #
# x # # x # # # . # x #
# x x x x # # # . # x #
# # . # . # # # . # x A
# # . # # # . . . # # #
# # # # # # # # # # # #