算法1
BFS
Java 代码
import java.io.*;
import java.util.*;
class Main{
static int n, m;
static int[][] grid;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s1 = br.readLine().split("\\s+");
n = Integer.valueOf(s1[0]);
m = Integer.valueOf(s1[1]);
int[][] dirs = {{1,0}, {-1, 0}, {0, -1}, {0, 1}};
Queue<int[]> q = new LinkedList<>();
int[][] d = new int[n][m];
grid = new int[n][m];
//迷宫grid
for(int i = 0; i < n; i++) {
String[] s = br.readLine().split("\\s+");
for (int j = 0; j < m; j++) {
grid[i][j] = Integer.parseInt(s[j]);
}
}
q.add(new int[]{0, 0});
while(!q.isEmpty()){
int[] node = q.poll();
for(int[] dir: dirs){
int x = node[0] + dir[0];
int y = node[1] + dir[1];
if(isValid(x, y, grid, d)){
q.add(new int[]{x, y});
d[x][y] = d[node[0]][node[1]] + 1;
}
}
}
System.out.print(d[n-1][m-1]);
}
private static boolean isValid(int x, int y, int[][] grid, int[][] d){
return x >= 0 && x < grid.length && y >= 0 && y < m && grid[x][y] == 0 && d[x][y] == 0;
}
}