import java.util.ArrayList;
import java.util.List;
public class Road {
static public int[][] map =
{{1,0,1,1,1,1,0,1},
{1,1,0,1,1,1,0,1},
{1,1,0,1,0,1,0,1},
{1,1,1,1,1,0,1,1},
{1,1,0,1,1,1,1,1}};
public static void main(String[] args) {
//初始化数据
for (int i = 0; i < getMapX(); i++) {
for (int j = 0; j < getMapY(); j++) {
distance[i][j] = getNodeNum() + 1;//比总点数还多1,表示永远无法触达,即路障
reached[i][j] = 0;//标记为未触达
}
}
distance[0][0] = 0;//起始点距离为0
reached[0][0] = 1;//起始点标记已触达,避免重复执行
startNodeList.add(new StartNode(0, 0,0));//将[0][0]点作为开始节点,加入待触达列表
while (!startNodeList.isEmpty()) {
StartNode startNode = getMinDistanceNode(startNodeList);//获取临近点中距离最短点
List<int[]> cabeNodeList = getCabeNode(startNode.x, startNode.y);//获取邻居节点列表
for (int[] xy : cabeNodeList) {
if (distance[xy[0]][xy[1]] > distance[startNode.x][startNode.y] + 1) {//只保存最短距离
distance[xy[0]][xy[1]] = distance[startNode.x][startNode.y] + 1;
printDistance();//打印每一步操作
}
if (reached[xy[0]][xy[1]] == 0) {
reached[xy[0]][xy[1]] = 1;//标记为已触达
startNodeList.add(new StartNode(xy[0], xy[1], distance[xy[0]][xy[1]]));//将未处理的点加入队列
}
}
startNodeList.remove(startNode);//去除已处理的点
}
}
static int step = 0;
static void printDistance(){
System.out.println("Step:" + ++step);
for (int i = 0; i < getMapX(); i++) {
for (int j = 0; j < getMapY(); j++) {
System.out.print(distance[i][j]+"\t");
}
System.out.println();
}
System.out.println();
}
static List<StartNode> startNodeList = new ArrayList<StartNode>();
static List<int[]> getCabeNode(int x, int y) {
List<int[]> list = new ArrayList<int[]>();
if (x - 1 >= 0 && map[x - 1][y] != 0) {//去除路障
list.add(new int[]{x - 1, y});
}
if (y - 1 >= 0 && map[x][y - 1] != 0) {
list.add(new int[]{x, y - 1});
}
if (x + 1 <= getMapX() - 1 && map[x + 1][y] != 0) {
list.add(new int[]{x + 1, y});
}
if (y + 1 <= getMapY() - 1 && map[x][y + 1] != 0) {
list.add(new int[]{x, y + 1});
}
return list;
}
public static int[][] distance = new int[getMapX()][getMapY()];
public static int[][] reached = new int[getMapX()][getMapY()];
public static int getNodeNum() {
return getMapX() * getMapY();
}
static public int getMapX (){
return map.length;
}
static public int getMapY (){
return map[0].length;
}
static class StartNode {
int x;
int y;
int distance;
StartNode(int x, int y, int distance) {
this.distance = distance;
this.x = x;
this.y = y;
}
}
static StartNode getMinDistanceNode(List<StartNode> list) {
int index = 0;
int minDistance = list.get(0).distance;
int minIndex = 0;
for (StartNode node : list) {
if (node.distance < minDistance) {
minDistance = node.distance;
minIndex = index;
}
index++;
}
return list.get(minIndex);
}
}