Grind75 Notes
  • README
  • week-1
    • Two Sum
    • Valid Parentheses
    • Merge Two Sorted Lists
    • Best Time to Buy and Sell Stock
    • Valid Palindrome
    • Invert Binary Tree
    • Valid Anagram
    • Binary Search
    • Flood Fill
    • Lowest Common Ancestor of a Binary Search Tree
    • Balanced Binary Tree
    • Linked List Cycle
    • Implement Queue using Stacks
  • week-2
    • First Bad Version
    • Ransom Note
    • Climbing Stairs
    • Longest Palindrome
    • Reverse Linked List
    • Majority Element
    • Add Binary
    • Diameter of Binary Tree
    • Middle of the Linked List
    • Maximum Depth of Binary Tree
    • Contains Duplicate
    • Maximum Subarray
  • week-3
    • Insert Interval
    • 01 Matrix
    • K Closest Points to Origin
    • Longest Substring Without Repeating Characters
    • 3Sum
    • Binary Tree Level Order Traversal
    • Clone Graph
    • Evaluate Reverse Polish Notation
  • week-4
    • Course Schedule
    • Implement Trie (Prefix Tree)
    • Coin Change
    • Product of Array Except Self
    • Min Stack
    • Validate Binary Search Tree
    • Number of Islands
    • Rotting Oranges
  • week-5
    • Search in Rotated Sorted Array
    • Combination Sum
    • Permutations
    • Merge Intervals
    • Lowest Common Ancestor of a Binary Tree
    • Time Based Key-Value Store
    • Accounts Merge
    • Sort Colors
  • week-6
    • Word Break
    • Partition Equal Subset Sum
    • String to Integer (atoi)
    • Spiral Matrix
    • Subsets
    • Binary Tree Right Side View
    • Longest Palindromic Substring
    • Unique Paths
    • Construct Binary Tree from Preorder and Inorder Traversal
  • week-7
    • Container With Most Water
    • Letter Combinations of a Phone Number
    • Word Search
    • Find All Anagrams in a String
    • Minimum Height Trees
    • Task Scheduler
    • LRU Cache
  • week-8
    • Kth Smallest Element in a BST
    • Minimum Window Substring
    • Serialize and Deserialize Binary Tree
    • Trapping Rain Water
    • Find Median from Data Stream
    • Word Ladder
    • Basic Calculator
    • Maximum Profit in Job Scheduling
    • Merge k Sorted Lists
    • Largest Rectangle in Histogram
Powered by GitBook
On this page
  • Problem
  • Pseudocode
  • Solution
  • Time and Space Complexity
  1. week-4

Rotting Oranges

PreviousNumber of IslandsNextweek-5

Last updated 2 years ago

Problem

You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell,

  • 1 representing a fresh orange, or

  • 2 representing a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

Example 1:

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

Example 2:

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.

Example 3:

Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

Pseudocode

- bfs to look for fresh oranges starting from rotten oranges, moving in 4 directions
    - reassign values of fresh oranges, to distance from rotten oranges

Solution

var orangesRotting = function (grid) {
  if (!grid || grid.length === 0) {
    return 0;
  }

  const row = grid.length;
  const column = grid[0].length;
  const queue = [];
  let countFresh = 0;
  let minutes = 0;
  let dirs = [
    [1, 0],
    [-1, 0],
    [0, 1],
    [0, -1],
  ];

  // put the position of all rotten oranges in queue
  // count the number of fresh oranges
  for (let i = 0; i < row; i++) {
    for (let j = 0; j < column; j++) {
      if (grid[i][j] === 2) {
        queue.push([i, j]);
      }

      if (grid[i][j] === 1) {
        countFresh++;
      }
    }
  }

  // if count of fresh oranges is zero, return zero

  if (countFresh === 0) {
    return 0;
  }

  // bfs starting from initially rotten oranges
  while (queue.length !== 0 && countFresh) {
    minutes++;
    let size = queue.length; // set the size before hand,
    for (let i = 0; i < size; i++) {
      // if i is limited by queue.length i.e. i < queue.length, queue.length will be vary dynamically
      const point = queue.shift();

      for (const dir of dirs) {
        const x = point[0] + dir[0];
        const y = point[1] + dir[1];

        // set when to continue, out of bounds, already rotten or empty cell
        if (
          x < 0 ||
          y < 0 ||
          x >= row ||
          y >= column ||
          grid[x][y] === 2 ||
          grid[x][y] === 0
        ) {
          continue;
        }

        // if code reaches here, orange is fresh, mark is as rotten
        grid[x][y] = 2;

        // book keeping, if not all fresh oranges are rotten, return -1
        countFresh--;

        // push this the coords of this newly rotten orange into queue to look for next fresh orange
        queue.push([x, y]);
      }
    }
  }
  // count - 1 because minute is 0 based index
  return countFresh === 0 ? minutes : -1;
};

Time and Space Complexity

Time

  • What did the code do

  • Total -

Space

  • What did the code do

  • Total -

Loading...LeetCode
Logo