- Rotting Oranges
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
题意 :就是有个棋盘,然后里面可能有坏的橘子,好的橘子,空的,分为用2,1, 0 表示,然后一个橘子坏掉了,在接下来的1s里,周围4个方向的橘子都会坏掉。问,最后最少多长时间全部坏掉。
解析:其实就是BFS的应用,首先遍历一遍棋盘,如果存在一个好的橘子4个方向都都是空,那么直接返回-1,因为它不会被坏掉。然后就是BFS了,每次取队列里所有为2的节点,然后进行扩展,如果某一次,有橘子没有被感染,但是队列里又没有坏的橘子了,说明存在大于1个的联通分量,那么返回-1. 否则最后的结果就是BFS的层数。
代码:
class Solution
{
public:
bool judge(int x, int y, int rows, int cols)
{
if (x<0 || y<0 || x>rows || y>cols) return false;
return true;
}
struct Node
{
int x, y;
};
int orangesRotting(vector<vector<int>>& grid)
{
int dx[4] = { -1, 1, 0, 0 };
int dy[4] = { 0, 0, -1, 1 };
int rows = grid.size();
int cols = grid[0].size();
bool flag;
int o2 = 0; // 坏橘子的个数
int cnt = 0; // 橘子数量
int blank = 0;
queue<Node> Q;
Node cur;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j <cols; j++)
{
if (!grid[i][j]) ++blank;
if (grid[i][j]) ++cnt; //橘子数量
if (grid[i][j] == 2)
{
cur.x = i;
cur.y = j;
Q.push(cur);
++o2;
}
if (grid[i][j] == 1)
{
bool flag = true;
for (int k = 0; k < 4; k++)
{
int xx = i + dx[k];
int yy = j + dy[k];
if (judge(xx, yy, rows - 1, cols - 1) && (grid[xx][yy] == 1 || grid[xx][yy] == 2))
{
flag = false;
break;
}
}
if (flag) return -1;
}
}
}
if (blank == rows*cols) return 0;
if (o2 == 0) return -1;
//cout << o2 << " " << cnt << endl;
int ans = 0;
while (cnt!= o2)
{
int size = Q.size();
if (size == 0) return -1;
++ans;
while (size)
{
Node cur = Q.front();
Q.pop();
--size;
for (int i = 0; i < 4; i++)
{
int xx = cur.x + dx[i];
int yy = cur.y + dy[i];
if (judge(xx, yy, rows - 1, cols - 1) && grid[xx][yy] == 1)
{
++o2;
grid[xx][yy] = 2;
Node tmp;
tmp.x = xx;
tmp.y = yy;
Q.push(tmp);
}
}
}
}
return ans;
}
};