連結:https://leetcode.com/problems/rotting-oranges/description/
class Solution {
public int orangesRotting(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] visited = grid;
Queue<int[]> q = new LinkedList<>();
int countFreshOrange = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (visited[i][j] == 2) {
q.offer(new int[] {i, j});
}
if (visited[i][j] == 1) {
countFreshOrange++;
}
}
}
if (countFreshOrange == 0)
return 0;
if (q.isEmpty())
return -1;
int minutes = -1;
int[][] dirs = {{1, 0},{-1, 0},{0, -1},{0, 1}};
while (!q.isEmpty()) {
int size = q.size();
while (size-- > 0) {
int[] cell = q.poll();
int x = cell[0];
int y = cell[1];
for (int[] dir : dirs) {
int i = x + dir[0];
int j = y + dir[1];
if (i >= 0 && i < m && j >= 0 && j < n && visited[i][j] == 1) {
visited[i][j] = 2;
countFreshOrange--;
q.offer(new int[] {i, j});
}
}
}
minutes++;
}
if (countFreshOrange == 0)
return minutes;
return -1;
}
}
連結:https://leetcode.com/problems/shortest-path-in-binary-matrix/description/
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
int d1[] = {0,-1,-1,-1,0,1,1,1};
int d2[] = {-1,-1,0,1,1,1,0,-1};
if(grid[0][0] == 1){
return -1;
}
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{0, 0});
int dist = 0;
while(!q.isEmpty()){
int size = q.size();
for(int i = 0; i< size;i++){
int temp []= q.poll();
int row = temp[0];
int col = temp[1];
if(row == grid.length-1 && col == grid[0].length-1){
return dist + 1;
}
for(int dir = 0;dir < 8;dir++){
int next_row = row+ d1[dir];
int next_col = col + d2[dir];
if(next_row < 0 || next_col < 0 || next_row >= grid.length || next_col >= grid[0].length || grid[next_row][next_col] == 1){
continue;
}
q.add(new int[]{next_row, next_col});
grid[next_row][next_col] = 1;
}
}
dist++;
}
return -1;
}
}