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;
}
};
Difficulty
and has an acceptance rate of about 59% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Matrix
AI Disclaimer
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.
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:
-
If
numFreshis 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; } -
If no new oranges became rotten (
newRotten == 0) while fresh oranges still exist, the function returns-1to indicate impossibility:if (newRotten == 0) return -1; -
Otherwise, the
gridis updated to thenextstate 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 286: Walls and Gates
- problem 317: Shortest Distance from All Buildings
- problem 419: Battleships in a Board
- problem 2101: Detonate the Maximum Bombs
- problem 2258: Escape the Spreading Fire
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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