1、问题描述
输入n和m表示迷宫的行数和列数,接下俩输入迷宫的状态,使用深度优先搜寻即可求出最短距离
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
2、代码实现
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int n;
static int m;
static int[][] map;
static int ans = 0;
static boolean[][] visit;
static int[] xs = {1,0,0,-1};
static int[] ys = {0,1,-1,0};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
map = new int[n][m];
//0表示可以走,1表示障碍物
for(int i = 0;i < n;i++) {
for(int j = 0;j < m;j++) {
map[i][j] = scanner.nextInt();
}
}
visit = new boolean[n][m];
ans = bfs();
System.out.println(ans);
}
public static int bfs() {
Queue<Node> queue = new ArrayDeque<>();
//入队
queue.offer(new Node(0,0,0));
//设置已访问
visit[0][0] = true;
while(!queue.isEmpty()) {
//出队
Node node = queue.poll();
//是否到达终点
if(node.x == n - 1 && node.y == m - 1) {
return node.step;
}
int step = node.step;
for(int i = 0;i < 4;i++) {
//遍历四个方向
int x = node.x + xs[i];
int y = node.y + ys[i];
if(x >= 0 && x < n && y >= 0 && y < m && !visit[x][y] && map[x][y] == 0) {
System.out.println(node);
queue.offer(new Node(x,y,step + 1));
visit[x][y] = true;
}
}
}
return -1;
}
}
class Node{
int x;
int y;
int step;
public Node(int x, int y, int step) {
super();
this.x = x;
this.y = y;
this.step = step;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return x + "=" + y + "=" + step;
}
}