Rotting Oranges Medium / #994 / grid
A grid holds empty cells, fresh oranges and rotten ones. Every minute each rotten orange spoils the fresh oranges right above, below, left and right of it. Find how many minutes pass until no fresh orange is left, or -1 if some never rot. Our example: RFF. / F.FF / FF.R (R rotten, F fresh, . empty) — the answer is 3.
input grid: an m × n grid, each cell 0 empty, 1 a fresh orange or 2 a rotten one. returns How many minutes pass until no fresh orange is left, or -1 if some never rot. Every minute each rotten orange spoils the fresh ones right above, below, left and right of it. constraints m = grid.length, n = grid[i].length, 1 ≤ m, n ≤ 10 grid[i][j] is 0, 1 or 2 our 14 tests keep to them examples Open a test in the tests panel: it shows the input and the expected answer. walkthrough solve timer --:-- off
switch language → JavaScript TypeScript Python Go Java submit only: no test in the browserC++ submit only: no test in the browserother /**
* @param {number[][]} grid
* @return {number}
*/
function orangesRotting(grid) {
}
test submit
14 tests · limit 3 s
01 — grid = [[2, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 2]] copy 02 — grid = [[2, 1, 0], [0, 0, 0], [0, 0, 1]] copy 03 — grid = [[2, 0, 2]] copy 04 — grid = [[0, 0], [0, 0]] copy 05 — grid = [[1]] copy 06 — grid = [[2, 1, 1, 1, 1]] copy 07 — grid = [[2, 1, 1, 1, 1, 2]] copy 08 — grid = [[1, 1, 1, 2, 2, 0], [0, 0, 0, 1, 0, 2], [2, 1, 2, 1, 0, 1], [2, 0, 1, 2, 1, 1], [1, 1, 1, 0, 1, 2]] copy 09 — grid = [[1, 0, 1, 0, 2, 1, 1, 1, 1, 1], [0, 2, 1, 1, 0, 2, 0, 1, 2, 1], [0, 1, 1, 0, 1, 1, 1, 1, 2, 1], [1, 2, 2, 1, 1, 1, 1, 1, 1, 2], [1, 0, 2, 1, 1, 2, 2, 1, 1, 2], [1, 1, 1, 1, 0, 2, 1, 1, 1, 0], [1, 2, 1, 1, 2, 0, 1, 2, 1, 1], [1, 1, 1, 1, 1, 1, 2, 1, 1, 1], [2, 2, 2, 2, 1, 1, 1, 0, 1, 2], [1,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, 2, 2, 2, 0], [0, 2, 2, 0, 0, 2, 0, 2, 2, 2], [2, 0, 2, 0, 2, 0, 2, 0, 0, 2]] copy 14 — grid = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] copy
Stuck? See the solution run step by step on our example, then why it works and its complexity.
Watch the walkthrough → The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.