package com.qjh.maze;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Maze2
{
private int y = 0;//地图高度
private int x = 0;//地图宽度
class Cell// 内部类
{
private int row;
private int col;
private Cell from;// 指向父节点
public Cell(int row, int col, Cell from)
{
this.row = row;
this.col = col;
this.from = from;
}
@Override
public String toString() {
return "row = " + this.row + ",col = " + this.col;
}
}
String[][] maze =
{ { "1", "1", "1", "0", "0", "0", "0", "0" },
{ "1", "0", "1", "0", "1", "1", "1", "1" },
{ "1", "0", "0", "0", "0", "0", "0", "1" },
{ "1", "1", "1", "1", "1", "1", "1", "1" } };
public void show()
{
for (int i = 0; i < maze.length; i++)
{
for (int j = 0; j < maze[i].length; j++)
System.out.print(" " + maze[i][j]);
System.out.println();
}
}
// 把与from集合中相邻的可染色节点染色,被染色节点记入 dest
// 一旦发现出口将被染色,则返回当前的“传播源”节点
public Cell colorCell(Set from, Set dest)
{
Iterator it = from.iterator();
while (it.hasNext())
{
Cell a = it.next();
Cell[] c = new Cell[4];
c[0] = new Cell(a.row - 1, a.col, a); // 向上
c[1] = new Cell(a.row, a.col - 1, a); // 向左
c[2] = new Cell(a.row + 1, a.col, a); // 向下
c[3] = new Cell(a.row, a.col + 1, a); // 向右
for (int i = 0; i < 4; i++)
{
if (c[i].row < 0 || c[i].row >= maze.length)
continue;
if (c[i].col < 0 || c[i].col >= maze[0].length)
continue;
String x = maze[c[i].row][c[i].col];//获取迷宫地图对应的节点元素
if (c[i].row == 0 && c[i].col == 0) {
return new Cell(c[i].row, c[i].col, a);// 获取入口元素以及它的父节点
}
if (x == "1")
{
maze[c[i].row][c[i].col] = "?";// 对可通过路径进行标记
dest.add(c[i]);
}
}
}
return null;
}
public void resolve()
{
y = maze.length;
x = maze[0].length;
Set set = new HashSet();
set.add(new Cell(y-1, x-1, null));//从出口节点开始找
for (;;)
{
Set set1 = new HashSet();
Cell a = colorCell(set, set1);
if (a != null)
{
System.out.println("找到出路了!");
while (a != null)
{
int r = a.row;
int c = a.col;
int index = r * x + (c + 1);//获取元素索引编号
maze[r][c] = index + "";// 标出通路路径
System.out.print(index + " ");
a = a.from;
}
break;
}
if (set1.isEmpty())
{
System.out.println("无解!");
break;
}
set = set1;
}
}
public static void main(String[] args)
{
Maze2 m = new Maze2();
m.show();
m.resolve();
}
}