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.
Press enter or click to view image in full size
The code is clean and the variable names should be self explanatory, let me know if you have trouble understanding something.