leetcode994. 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.
在這裏插入圖片描述
簡單來說,就是網格中0表示空,1表示新鮮水果,2表示腐爛水果,每個腐爛水果能在一分鐘之後把與它相鄰(上下左右)的新鮮水果變爛,問至少需要多長時間所有水果變爛。
本文采用BFS遍歷,藉助queue<vector>存儲腐爛蘋果

  • 從腐爛位置遍歷四個方向,將新一輪的腐爛蘋果入隊
  • 向queue裏push時要考慮不能添加已經遍歷過的位置
  • 記錄起始新鮮水果個數,判斷是否有孤立水果(return -1)
int orangesRotting(vector<vector<int>>& grid) {
        //廣度優先搜索遍歷
        int fresh = 0,rot = 0,ans=0;
        int row = grid.size();
        int col = grid[0].size();
        int dx[4] = {0,0,1,-1};
        int dy[4] = {1,-1,0,0};
        queue<vector<int>> queRot;
        vector<int> tmpRot;
        for(int i = 0;i < row;i++)
        {
            for(int j = 0;j < col;j++)
            {
                if(grid[i][j] == 1) fresh++;
                if(grid[i][j] == 2)
                {
                    rot++;
                    queRot.push({i,j});
                }
            }
        }
        while(!queRot.empty())
        {
            int curRot = rot;
            rot = 0;
            while(curRot--)
            {
                tmpRot = queRot.front();
                queRot.pop();
                int x,y;
                for(int i = 0;i < 4;i++)
                {
                    x = tmpRot[0] + dx[i];
                    y = tmpRot[1] + dy[i];
                    if(x<0||y<0||x>=row||y>=col||grid[x][y]!=1) continue;
                    grid[x][y] = 2;
                    queRot.push({x,y});
                    fresh--;
                    rot++;
                }
            }
            ans++;
        }
        if(fresh) return -1;
        else return max(0,ans-1);
    }
int main(){
	//case1: { {2,1,1},{1,1,0},{0,1,1} }
	vector<vector<int> >test1 = { {2,1,1},{1,1,0},{0,1,1} };
	cout << orangesRotting(test1) << endl;
	//case2:  {{2,1,1},{0,1,1},{1,0,1}}
	vector<vector<int> >test2 = { { 2,1,1 },{ 0,1,1 },{ 1,0,1 } };
	cout << orangesRotting(test2) << endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章