Rotting Oranges Leetcode
Rotting Oranges - LeetCode
You are given an m x n grid where each cell can have one of three values: 0 representing an empty cell, 1 representing…
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.
- I started out with keeping track of rotten orange’s co-ordinates(x,y) and freshOranges by traversing through the Grid
- We’ll also keep track of minutesElapsed variable and increment it, the number of times we loop through while.
- 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
- We assign this new vector back to original vector and continue till either freshOranges become zero or our track of rottenOranges becomes zero
- 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.