```javaimport java.util.*;
public class Main {
static int x, y;
// 图
static int[][] grahp;
// 记录每个点到起点的距离
static int[][] distance;
static class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
x = scan.nextInt();
y = scan.nextInt();
grahp = new int[x][y];
distance = new int[x][y];
for (int i = 0; i < x; i++ ){
for (int j = 0; j < y; j++) {
grahp[i][j] = scan.nextInt();
}
}
System.out.println(bfs());
}
static int bfs() {
int head = 0, tail = 0;
Queue<Node> queue = new LinkedList();
queue.offer(new Node(0,0));
// 向量. 分别代表一个点的上下左右4个端点坐标.
// 垂直向量. 顺序代表上下左右
int[] verticalVector = new int[]{0, 1, 0, -1};
// 水平向量. 顺序代表上下左右
int[] horizontalVector = new int[]{-1, 0, 1, 0};
while (!queue.isEmpty()) {
Node h = queue.poll();
// 谁先走到就立即退出.
if (h.x == x - 1 && h.y == y - 1) {
break;
}
for (int i = 0; i < 4; i++) {
int _x = h.x + verticalVector[i];
int _y = h.y + horizontalVector[i];
// 判断是否在边界内
// 并且该位置可以走, 且没有走过
if (_x >=0 && _y >=0 && _x < x && _y < y && grahp[_x][_y] == 0 && distance[_x][_y] == 0) {
distance[_x][_y] = distance[h.x][h.y] + 1;
queue.offer(new Node(_x, _y));
}
}
}
return distance[x - 1][y - 1];
}
}
```