迷宫
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class 迷宫问题 {
static int n;
static int m;
static int[] dx = { 1, 0, -1, 0 };
static int[] dy = { 0, 1, 0, -1 };
static char[][] maze;
public static class Node {
public int x;
public int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
sc.nextLine();
maze = new char[n][m];
for (int i = 0; i < maze.length; i++) {
maze[i] = sc.nextLine().toCharArray();
}
int ans = bfs();
System.out.println(ans);
}
private static int bfs() {
int sx = 0, sy = 1, gx = n - 1, gy = m - 2;
int[][] d = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
d[i][j] = -1;
}
}
Queue<Node> que = new LinkedList<>();
Node firstNode = new Node(sx, sy);
que.add(firstNode);
d[sx][sy] = 0;
while (!que.isEmpty()) {
Node curNode = que.poll();
int cx = curNode.x;
int cy = curNode.y;
if (cx == gx && cy == gy) {
return d[gx][gy];
}
for (int i = 0; i < 4; i++) {
int nx = cx + dx[i];
int ny = cy + dy[i];
if ((0 <= nx && nx < n) && (0 <= ny && ny < m) && (d[nx][ny] == -1) && (maze[nx][ny] != '#')) {
Node nextNode = new Node(nx, ny);
que.add(nextNode);
d[nx][ny] = d[cx][cy] + 1;
}
}
}
return d[gx][gy];
}
}