一、题目
二、代码
class Solution
{
//求最小值 应该用广度优先
//dfs 堆栈
//bfs 递归
int[][] moved= {{0,1},{0,-1},{1,0},{-1,0}};
public int orangesRotting(int[][] grid)
{
//包装过后的层序遍历
int i,j;
int length_1 = grid.length;
int length_2 = grid[0].length;
int result = 0;
Queue<int[]> re = new LinkedList<>();
int count = 0;
for(i=0;i<length_1;i++)
{
for(j=0;j<length_2;j++)
{
if(grid[i][j] == 1) count++;
if(grid[i][j] == 2)
{
int[] temp = new int[2];
temp[0] = i;
temp[1] = j;
re.offer(temp);
}
}
}
if(count == 0 ) return 0;
while(!re.isEmpty())
{
result++;
// System.out.println(" 存在腐烂的橘子 result " +result);
int w,k;
int temp_length = re.size();
for(w=0;w<temp_length;w++)
{
int[] temp_array = re.poll();
int temp_x = temp_array[0];
int temp_y = temp_array[1];
// System.out.println(" temp_x "+temp_x);
// System.out.println(" temp_y "+temp_y);
// System.out.println(" count " +count);
for(k=0;k<4;k++)
{
int next_x = temp_x + moved[k][0];
int next_y = temp_y + moved[k][1];
// System.out.println(" next_x "+next_x);
// System.out.println(" next_y "+next_y);
if(next_x>=0&&next_x<length_1&&next_y>=0&&next_y<length_2 && grid[next_x][next_y] == 1)
{
// System.out.println("进入腐烂流程");
grid[next_x][next_y] =2;
int[] temp = new int[2];
temp[0] = next_x;
temp[1] = next_y;
re.offer(temp);
count--;
}
}
}
}
System.out.println(" count " +count);
if(count>0) return -1;
//注释:最后一次会进入,但是找不到仍旧需要腐烂的橘子了
return result -1;
}
}