</>

994. Rotting Oranges

Medium NeetCode 150
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Graphs
Time
—
Space
—

Standard Solution (C++)

SummaryGiven a 2D grid where cells contain empty space (0), fresh oranges (1), or rotten oranges (2), determine the minimum number of minutes until all fresh oranges are rotten — where each minute, every rotten orange spreads to its 4-adjacent neighbors — or return -1 if any fresh orange can never be reached.

Approach
  • Multi-source BFS: seed the queue with all initially-rotten oranges simultaneously so spreading propagates in parallel from every rotten cell, exactly modeling the one-minute-per-wave constraint.
  • Count fresh oranges upfront; each time BFS infects a neighbor, decrement the counter so a final check detects isolated fresh oranges.
  • Track elapsed time by counting completed BFS levels (waves), incrementing only when a wave actually produced new rotten oranges.
  • If fresh count is non-zero after BFS exhausts, return -1; otherwise return the elapsed minutes.
#include <vector>
#include <queue>
using namespace std;

class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
        int rows = grid.size(), cols = grid[0].size();
        queue<pair<int,int>> q;
        int fresh = 0;

        // Seed queue with all rotten oranges; count fresh ones.
        for (int r = 0; r < rows; ++r)
            for (int c = 0; c < cols; ++c)
                if (grid[r][c] == 2) q.push({r, c});
                else if (grid[r][c] == 1) ++fresh;

        if (fresh == 0) return 0;  // nothing to rot

        const int dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
        int minutes = 0;

        // BFS level-by-level; each level = one minute.
        while (!q.empty() && fresh > 0) {
            int sz = q.size();
            ++minutes;
            while (sz--) {
                auto [r, c] = q.front(); q.pop();
                for (auto& d : dirs) {
                    int nr = r + d[0], nc = c + d[1];
                    if (nr >= 0 && nr < rows && nc >= 0 && nc < cols
                            && grid[nr][nc] == 1) {
                        grid[nr][nc] = 2;  // mark rotten in-place (no extra visited set needed)
                        --fresh;
                        q.push({nr, nc});
                    }
                }
            }
        }

        return fresh == 0 ? minutes : -1;
    }
};
Time O(M * N) Space O(M * N)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
        // use bfs to solve the problem
        queue<pair<int, int>> q; // store rotten oranges
        int freshCount=0;
        int time=0;

        for(int i=0; i<grid.size(); ++i){
            for(int j=0; j<grid[0].size(); ++j){
                if(grid[i][j]==0)
                    continue;
                else if(grid[i][j]==1)
                    ++freshCount;
                else // grid[i][j]==2
                    q.push({i, j});
            }
        }

        if(freshCount==0)
            return 0;

        vector<pair<int,int>> directions={{0,1}, {0,-1}, {1,0}, {-1,0}};

        while(!q.empty()){

            int curNum=q.size();

            for(int i=0; i<curNum; ++i){
                auto cur=q.front();
                q.pop();

                int row=cur.first;
                int col=cur.second;

                for(auto& dir: directions){
                    int x=row+dir.first;
                    int y=col+dir.second;

                    if(x>=0 && y>=0 && x<grid.size() && y<grid[0].size() && grid[x][y]==1){
                        grid[x][y]=2;
                        q.push({x,y});
                        --freshCount;
                    }
                }
            }
            if(!q.empty())
                ++time;
        }

        if(freshCount!=0)
            return -1;

        return time;
    }
};

// Time: O(M*N)
// Space: O(M*N), for the queue to store the rotten oranges

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern