Rotting Oranges Leetcode

ad1tyaV
1 min readJun 13, 2021

--

This is one of the classic BFS Problems(I guess you could solve using DFS too) and a great one too.

Here’s one of the ways to solve it.

  1. I started out with keeping track of rotten orange’s co-ordinates(x,y) and freshOranges by traversing through the Grid
  2. We’ll also keep track of minutesElapsed variable and increment it, the number of times we loop through while.
  3. We continuously poll the first element from rottenOranges vector and traverse (top, down, left, right), if we hit a fresh orange:
    a) We decrement freshOranges count
    b) We add this rottedOrange co-ordinates to new vector
  4. We assign this new vector back to original vector and continue till either freshOranges become zero or our track of rottenOranges becomes zero
  5. At the end if freshOranges aren’t zero, return -1, else return minutesElapsed variable.

The code is clean and the variable names should be self explanatory, let me know if you have trouble understanding something.

Code for the same can be found here:

Thanks for reading!, clap if it helped you.

--

--