Rotting Oranges
Each cell of an m x n grid holds one of three values:
0: an empty cell1: a fresh orange2: a rotten orange
Every minute, each fresh orange that is directly above, below, left or right of a rotten orange becomes rotten. All the rotten oranges spread at the same time.
Return the number of minutes that pass until no fresh orange is left. If some fresh orange can never rot, return -1. If there are no fresh oranges at the start, the answer is 0.
Constraints
1 <= m, n <= 10grid[r][c]is0,1or2
Examples
Example 1
Input: grid = [[2,1,1,0],[0,1,0,1],[1,1,1,1]] Output: 6
The rot spreads one step per minute: (0,1) at minute 1, (0,2) and (1,1) at 2, (2,1) at 3, (2,0) and (2,2) at 4, (2,3) at 5 and finally (1,3) at 6.
Example 2
Input: grid = [[2,1,0],[0,1,0],[1,0,1]] Output: -1
The oranges at (2,0) and (2,2) have no rotten neighbour, ever: empty cells cut them off. So it's impossible: -1.
Example 3
Input: grid = [[0,2,0]] Output: 0
There are no fresh oranges at all, so no time needs to pass: 0.
JavaScript you'll use: Graphs and grids in JavaScript Stacks, queues and deques
/**
* @param {number[][]} grid
* @return {number}
*/
function orangesRotting(grid) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.