Problem 994

Abstract / Summary

Given a grid of oranges some are rotten each minute all fresh oranges next to a rotten one become rotten find the time until no fresh remain.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0994.cpp

class Solution {
public:
    int orangesRotting(vector<vector<int>>& grid) {
        int w = grid.size();
        int h = grid[0].size();

        int result = 0;
        for (; ; result++)
        {
            int newRotten = 0;
            int numFresh = 0;
            auto next = grid;

            for (int x = 0; x < w; x++)
                for (int y = 0; y < h; y++)
                {
                    if (grid[x][y] != 1)
                        continue;

                    bool rot = false;
                    if (x > 0 && grid[x-1][y] == 2)
                        rot = true;
                    if (y > 0 && grid[x][y-1] == 2)
                        rot = true;
                    if (x < w-1 && grid[x+1][y] == 2)
                        rot = true;
                    if (y < h-1 && grid[x][y+1] == 2)
                        rot = true;

                    if (rot)
                    {
                        newRotten++;
                        next[x][y] = 2;
                    }
                    else
                        numFresh++;
                }

            if (numFresh == 0)
            {
                if (newRotten > 0)
                    result++;
                break;
            }
            if (newRotten == 0)
                return -1;

            grid = next;
        }

        return result;
    }
};

53 lines | 1425 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “rotting oranges” problem using a breadth-first style simulation. It repeatedly scans the grid, turning fresh oranges adjacent to rotten ones into rotten oranges, and counts the minutes required until no fresh orange remains. The loop terminates either when all oranges are rotten, when no further spread is possible (returning -1), or when the last conversion occurs, in which case the accumulated minute counter is returned.

Core Algorithm

The algorithm begins by extracting the dimensions of the input matrix:

int w = grid.size();
int h = grid[0].size();

A result variable is initialized to zero and serves as the minute counter. The outer for loop runs indefinitely, incrementing result at the start of each iteration:

int result = 0;
for (; ; result++)
{
    // body
}

Inside the loop a fresh copy of the current grid is created to hold the state for the next minute:

auto next = grid;

Two counters, newRotten and numFresh, track the number of oranges that become rotten during the current minute and the number of fresh oranges that remain untouched, respectively.

The nested for loops iterate over every cell:

for (int x = 0; x < w; x++)
    for (int y = 0; y < h; y++)
    {
        // body
    }

When a cell does not contain a fresh orange (grid[x][y] != 1) the iteration skips further processing. For a fresh orange, the code checks the four orthogonal neighbours for a rotten orange (2). If any neighbour is rotten, the flag rot becomes true:

bool rot = false;
if (x > 0 && grid[x-1][y] == 2) rot = true;
if (y > 0 && grid[x][y-1] == 2) rot = true;
if (x < w-1 && grid[x+1][y] == 2) rot = true;
if (y < h-1 && grid[x][y+1] == 2) rot = true;

When rot is true, the orange is marked as rotten in the next grid and newRotten is incremented; otherwise numFresh is incremented:

if (rot)
{
    newRotten++;
    next[x][y] = 2;
}
else
    numFresh++;

After scanning the entire grid, three termination conditions are evaluated:

  1. If numFresh is zero, all fresh oranges have been processed. If at least one orange turned rotten in this minute (newRotten > 0), the minute counter is incremented once more before breaking out of the loop:

     if (numFresh == 0)
     {
         if (newRotten > 0)
             result++;
         break;
     }
  2. If no new oranges became rotten (newRotten == 0) while fresh oranges still exist, the function returns -1 to indicate impossibility:

     if (newRotten == 0)
         return -1;
  3. Otherwise, the grid is updated to the next state and the loop proceeds to the next minute:

     grid = next;

Finally, the accumulated result is returned as the total minutes required:

return result;

Edge Cases Handled

The implementation gracefully handles an empty grid scenario by assuming at least one row and one column exist; the dimensions are derived directly from the input. When the grid contains only rotten oranges, the inner scan finds no fresh oranges (numFresh == 0) and the loop exits immediately with a result of zero minutes. If the grid contains fresh oranges but no rotten ones, the first iteration yields newRotten == 0 while numFresh remains positive, causing an early return of -1. The boundary checks (x > 0, x < w-1, y > 0, y < h-1) prevent out-of-range accesses when evaluating neighbours, ensuring correctness at the edges and corners of the matrix.

Performance Optimizations

The code avoids dynamic allocation inside the inner loops by reusing the next grid, which is a shallow copy of the current state created once per minute. This approach eliminates the need for per-cell memory operations during the spread phase. The neighbour checks are performed with simple conditional statements rather than more complex data structures, keeping the inner loop tight and cache-friendly. By incrementing the minute counter at the start of each outer iteration and adjusting it only when the final conversion occurs, the algorithm reduces unnecessary arithmetic operations. The early exit conditions (numFresh == 0 and newRotten == 0) prevent further unnecessary scans once a definitive outcome is known, cutting down on redundant work.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big grid filled with oranges. Some of these oranges are shiny and fresh, while others are already going rotten. Rot is a bit like a game of tag because a rotten orange will touch its neighbors and turn them rotten too.

This code acts like a clock that ticks one minute at a time. Every time the clock ticks, it looks at every single orange on the grid. It checks if a fresh orange is sitting right next to an orange that is already rotten. If a fresh orange has a rotten neighbor, it turns rotten when the next minute starts.

The code repeats this over and over. It keeps track of how many oranges change from fresh to rotten during each turn. If it reaches a point where there are no more fresh oranges left, the game is finished and it knows exactly how much time has passed while the rot was spreading. Sometimes, there might be a fresh orange trapped all by itself with no rotten neighbors to catch the rot from. If the code looks everywhere and sees that some oranges are still fresh but nobody around them is rotten, it knows the rot cannot reach them, so it stops trying.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.37 | σ = 1.75

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python C++ Java TS
WalkCCC C++
leetcode.ca Python C++ Java JS Go Rust TS
LeetcodeHelp Python C++ Java
Progiez Python C++ Java
github BigEggStudy C#
black-shadows C++
bujosa Python
charles-wangkai Java
everthis JS
fsq C++
Garvit244 Python
gouthampradhan Java
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
bujosa Python
charles-wangkai Java
everthis JavaScript
fsq C++
Garvit244 Python
gouthampradhan Java
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
37 links | 24 authors | 9 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality