一、题目描述
二、题目分析
本题是【岛屿问题】以及【图像渲染】的变形体,可参考之前总结的博文。
可参考【岛屿问题】:200. 岛屿数量
因此解题思路类似,都是【深度优先搜索】策略。
class Solution {
List<Integer> minDays = new ArrayList<Integer>();
int maxDay = -1;
public int orangesRotting(int[][] grid) {
if(grid == null) return -1;
int row = grid.length;
int col = grid[0].length;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(grid[i][j] == 2 )
dfs(grid, 0, i,j, row, col);
}
}
//这个时候进行遍历
for(int day : minDays){
maxDay = Math.max(maxDay,day);
}
return maxDay;
}
private int dfs(int[][] grid, int res, int i, int j, int row, int col){
//递归中止条件
if(i < 0 || j < 0 || i > row-1 || j > col-1){
return 0;
}
// 未放橘子,则直接返回
if(grid[i][j] == 0 ) return 0;
// 橘子已经烂了(且不是首次遍历),则直接返回
if(grid[i][j] == 2 && res != 0) return 0;
// 橘子未烂的,则变更为烂橘子
if(grid[i][j] == 1){
grid[i][j] = 2;
}
int top = dfs(grid, res+1, i-1, j, row, col);
int bto = dfs(grid, res+1, i+1, j, row, col);
int left = dfs(grid, res+1, i,j-1, row, col);
int right = dfs(grid, res+1, i, j+1, row, col);
//获取上下左右四个方向中,最大值
int[] compareRes = new int[4];
compareRes[0] = top; compareRes[1] = bto; compareRes[2] = left; compareRes[3] = right;
Arrays.sort(compareRes);
int maxRes = compareRes[3];
minDays.add(maxRes);
return res;
}
}
【未完待续】