26 · Graphs: BFS & DFS

#994 Rotting Oranges

Mediumsolve on LeetCode ↗

frequently reported atFlipkartAmazonSamsungWalmartInfosysMicrosoft

the problem

In plain words

Cells are 0 (empty), 1 (fresh orange) or 2 (rotten). Every minute, fresh oranges next to a rotten one (4 directions) rot. Return the minutes until no fresh orange is left, or -1 if that's impossible.

in grid = [[2,1,1],[1,1,0],[0,1,1]]

out 4

in grid = [[2,1,1],[0,1,1],[1,0,1]]

out -1

The bottom-left orange is never next to a rotten one.

in grid = [[0,2]]

out 0

No fresh oranges at minute 0.

  • 1 ≤ m, n ≤ 10
  • grid[i][j] ∈ {0, 1, 2}

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #542
      01 Matrix
      Mediumin Graphs
    2. #286
      Walls and Gates
      Mediumin GraphsLeetCode Premium
    3. #1091