In an N by N square grid, each cell is either empty (0) or blocked (1).
A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, …, C_k such that:
Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner)
C_1 is at location (0, 0) (ie. has value grid[0][0])
C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])
If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).
Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.
Example 1:
Input: [[0,1],[1,0]]
Output: 2
Example 2:
Input: [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
Note:
1 <= grid.length == grid[0].length <= 100
grid[i][j] is 0 or 1
求两点间最近的距离:BFS! BFS! BFS!
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
int n = grid.length;
if (grid[0][0] == 1 || grid[n-1][n-1] == 1) return -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) grid[i][j] = -1;
}
}
Queue<Node> queue = new LinkedList<>();
boolean[][] visited = new boolean[n][n];
queue.add(new Node(n-1, n-1, 1));
while (!queue.isEmpty()) {
Node node = queue.poll();
if (node.x < 0 || node.x >= n || node.y < 0 || node.y >= n || grid[node.x][node.y] == -1 || visited[node.x][node.y]) continue;
if (grid[node.x][node.y] == 0) {
grid[node.x][node.y] = node.v;
} else {
grid[node.x][node.y] = Math.min(grid[node.x][node.y], node.v);
}
int cur = grid[node.x][node.y];
// if (node.x == 0 && node.y == 0) break;
visited[node.x][node.y] = true;
queue.add(new Node(node.x + 1, node.y + 1, cur + 1));
queue.add(new Node(node.x + 1, node.y - 1, cur + 1));
queue.add(new Node(node.x - 1, node.y - 1, cur + 1));
queue.add(new Node(node.x - 1, node.y + 1, cur + 1));
queue.add(new Node(node.x, node.y + 1, cur + 1));
queue.add(new Node(node.x, node.y - 1, cur + 1));
queue.add(new Node(node.x + 1, node.y, cur + 1));
queue.add(new Node(node.x - 1, node.y, cur + 1));
}
return grid[0][0] == 0 ? -1 : grid[0][0];
}
public class Node{
int x;
int y;
int v;
public Node(int x, int y, int v) {
this.x = x;
this.y = y;
this.v = v;
}
}
}