Please use Laptop/Desktop or any other large screen for the Mock Interview Session.

Rotting Oranges and Minimum Falling Path Sum



YouTube Video Thumbnail
Link

Watch above sample mock interview video to see how it works.
Login and Buy Premium to Start the Interview



Rotting Fruit Problem

Rotting Fruit Problem

Problem Statement

You are given a 2D grid where each cell can hold one of three values:

  • 0 indicates an empty space;
  • 1 represents a fresh fruit;
  • 2 represents a spoiled fruit.

Every minute, any fresh fruit that is directly adjacent (up, down, left, right) to a spoiled fruit becomes spoiled as well.

Your task is to determine the smallest number of minutes that must pass until no fresh fruit remains in the grid. If it is not possible to spoil all fresh fruit, return -1.

Examples

Example 1:

grid = [[2,1,1],
        [1,1,0],
        [0,1,1]]
Output: 4

Example 2:

grid = [[2,1,1],
        [0,1,1],
        [1,0,1]]
Output: -1
Explanation: The fruit at bottom-left corner never spoils because spoiling only spreads in the four cardinal directions.

Example 3:

grid = [[0,2]]
Output: 0
Explanation: There are no fresh fruits at the start, so no time is needed.

Constraints

  • 1 ≤ number of rows in grid ≤ 12
  • 1 ≤ number of columns in grid[0] ≤ 12
  • Each grid cell value is either 0, 1, or 2.