zoukankan      html  css  js  c++  java
  • 腐烂的橘子

    题目链接:https://leetcode-cn.com/problems/rotting-oranges
    题目描述:
    在给定的网格中,每个单元格可以有以下三个值之一:

    值 0 代表空单元格;
    值 1 代表新鲜橘子;
    值 2 代表腐烂的橘子。
    每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。

    返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。

    题解:

    class Solution {
    public:
        int orangesRotting(vector<vector<int>>& grid) {
            int fresh = 0;
            queue <pair<int,int>> que;
            for(int i = 0; i < grid.size(); i++)
            {
                for(int j = 0; j < grid[0].size(); j++)
                {
                    if(grid[i][j] == 1)
                        fresh++;        //记录新鲜橘子个数
                    else if(grid[i][j] == 2)
                        que.push(make_pair(i, j));
                }
            }
            int time = 0;
            //上下左右四个方位
            int dx[4] = {1, 0, -1, 0};
            int dy[4] = {0, 1, 0, -1};
    
            while(!que.empty() && fresh > 0)
            {
                time++; 
                int len = que.size();           //记录初始烂橘子的个数
                for(int i = 0; i < len; i++){
                    pair<int, int> temp = que.front();      //获取烂橘子的位置
                    que.pop();
                    for(int j = 0; j < 4; j++)              //广度遍历烂橘子四周
                    {
                        int row = temp.first + dx[j];
                        int col = temp.second + dy[j];
                        if(row >=0 && row < grid.size() && col >=0 && col < grid[0].size() && grid[row][col] == 1)
                        {
                            grid[row][col] = 2;             //腐烂新鲜橘子
                            que.push(make_pair(row, col));
                            fresh--;
                        }
                    }
                }
                
            }
    
            if(fresh != 0)
                return -1;
            else
                return time;
        }
    
        
    };
    
    
  • 相关阅读:
    springboot2系列目录
    zookeeper 集群部署
    canal 配置 详细说明
    在Docker环境下部署Kafka
    Spring4新特性
    centos7 卸载 jdk
    Kafka安装
    Scala 面向对象(三):package 包 (二)
    Scala 基础(七):Scala 运算符
    Maven 专题(四):什么是Maven
  • 原文地址:https://www.cnblogs.com/ZigHello/p/15469332.html
Copyright © 2011-2022 走看看