Rotten Oranges

Given an N × M grid, 0 means empty, 1 means a fresh orange and 2 means a rotten orange. Every minute, any fresh orange next to a rotten orange up, right, down…

Given an N × M grid, 0 means empty, 1 means a fresh orange and 2 means a rotten orange. Every minute, any fresh orange next to a rotten orange up, right, down or left becomes rotten. All such changes happen simultaneously. Return the minimum minutes until no fresh oranges remain, or -1 if impossible. If no fresh oranges exist initially, return 0.

- 1 <= N, M <= 500 - grid is rectangular and cells are strict integers 0, 1 or 2 - The preset visualizer accepts grids up to 8×8; larger valid grids are execution-only.

Example 1: input grid = [[2,1,1],[0,1,1],[1,0,1]]; output -1. The fresh orange at(2,0) is blocked from every source by empty cells.

Example 2: input grid = [[2,1,1],[1,1,0],[0,1,1]]; output 4. Simultaneous four-directional waves rot the last fresh orange after four minutes.

Category: Graphs. Topic: graph. Difficulty: Medium. Patterns: graph-traversal.