BFS走四方
import java.util.LinkedList;
import java.util.Queue;
public class Main {
//方向
static final int[][] next = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
//迷宫
static int[][] map = {
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 1, 1, 1, 0},
{0, 0, 1, -1, 0, 0},
{0, 0, 1, 0, 0, 0},
};
//标记
static int[][] book = {
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
};
//队列
static Queue<Integer[]> queue = new LinkedList<>();
//每个点距离起点的距离
static int dis[][] = new int[6][6];
public static void main(String[] args) {
bfs(0, 0);
//打印标记
// for (int i = 0; i < book.length; i++) {
// for (int j = 0; j < book[0].length; j++) {
// System.out.print(book[i][j] + " ");
// }
// System.out.println();
// }
}
static void bfs(int x, int y) {
if (map[x][y] == -1) {
return;
}
//起点距离起点距离为0
dis[x][y] = 0;
//将起点入队
queue.offer(new Integer[]{x, y});
while (!queue.isEmpty()) {
//出队
Integer[] cur = queue.poll();
//走四方
for (int i = 0; i < 4; i++) {
int xx = cur[0] + next[i][0];
int yy = cur[1] + next[i][1];
if (xx >= 0
&& xx < map.length
&& yy >= 0
&& yy < map[0].length
&& book[xx][yy] != 1
) {
//标记
book[xx][yy] = 1;
//几点当前点距离起点的距离
dis[xx][yy] = dis[cur[0]][cur[1]] + 1;
//到达目标点
if (map[xx][yy] == -1) {
//System.out.printf("{%s, %s} %s\n", xx, yy, map[xx][yy]);
//打印目标点距离起点的最小距离
System.out.println("minDis:"+dis[xx][yy]);
return;
}
//System.out.printf("{%s, %s} %s\n", xx, yy, map[xx][yy]);
//入队
queue.offer(new Integer[]{xx, yy});
}
}
}
}
}