15% off all plans & roadmaps Use code
See plansLeetCode 994 · Solution & editorial
You are given an m x n grid where each cell can have one of three values:
Rotting Oranges is a Graph Traversal Patterns (DFS & BFS) problem, in the Graph BFS - Connected Components / Island Counting subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Use BFS for shortest path in unweighted graphs. Solve word ladder, rotting oranges, and matrix problems.
The reference solution runs in O(m * n) time and O(m * n) space.
Rotting Oranges has been reported in interviews at Amazon, Bloomberg, Flipkart, Google, Microsoft, Oracle, Walmart Labs.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Rotting Oranges is a Graph Traversal Patterns (DFS & BFS) problem, in the Graph BFS - Connected Components / Island Counting subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.