994. Rotting Oranges(Leetcode每日一题-2020.03.04)

Problem

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.

Note:

1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j] is only 0, 1, or 2.

Example1

在这里插入图片描述

Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Example2

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.

Example3

Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

Solution

2020-3-4
这道题的分类是简单。。。。
好吧,自己是在太弱了.。。。广度优先搜索写的少,不会。

这应该算一道典型的使用队列的BFS题目。

注意在棋盘上遍历四个方向的方式。

class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {

        queue<pair<int,int>> my_queue;
        int fresh_count = 0;
        int min = 0;

        for(int i = 0;i<grid.size();++i)
        {
            for(int j = 0;j<grid[0].size();++j)
            {
                if(grid[i][j] == 1)
                {
                    ++fresh_count;
                }
                else if(grid[i][j] == 2)
                {
                    my_queue.push(make_pair(i,j));
                }
            }
        }
		
		//用于四个方向的遍历
        vector<pair<int,int>> direction = {{-1,0},{1,0},{0,-1},{0,1}};

        while(!my_queue.empty())
        {
            //Get the number of the queue,ie number of rotten now
            int queue_size = my_queue.size();
            bool rotten = false;
            
            //Process each rotten
            for(int i = 0;i<queue_size;++i)
            {
                pair<int,int> cur = my_queue.front();
                my_queue.pop();

                //Four direction
                for(int j = 0;j<direction.size();++j)
                {
                    int x = cur.first - direction[j].first;
                    int y = cur.second - direction[j].second;

                    if(x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == 1)
                    {
                        grid[x][y] = 2;
                        my_queue.push(make_pair(x,y));
                        rotten = true;
                        --fresh_count;
                    }
                }   
            }

            if(rotten)
                ++min;
           
        }


        return fresh_count?-1:min;

    }

    
};
发布了496 篇原创文章 · 获赞 215 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/104660775