Rotting Oranges in C++

C++Server Side ProgrammingProgramming

Suppose we have a grid, here in each cell can have one of three values −

  • value 0 for an empty cell;

  • value 1 for a fresh orange;

  • value 2 for a rotten orange.

In every minute, any fresh orange that is adjacent to a rotten orange becomes rotten.

We have to find the minimum number of times that must elapse until no cell has a fresh orange. If this is not possible, then return -1.

So, if the input is like [[2,1,1],[1,1,0],[0,1,1]], then the output will be 4

To solve this, we will follow these steps −

  • minutes := 0

  • rowMax := row size of grid

  • colMax := col size of grid

  • freshLeft := false

  • newGrid := grid

  • while true is non-zero, do −

    • newGrid := grid

    • flag := false

    • freshLeft := false

    • for initialize i := 0, when i < rowMax, update (increase i by 1), do −

      • for initialize j := 0, when j < colMax, update (increase j by 1), do −

        • if newGrid[i, j] is same as 1, then −

          • if (i-1 >= 0 and newGrid[i-1,j] is 2) or (i+1 < rowMax and newGrid[i+1,j] is 2) or (j-1 >= 0 and newGrid[i,j-1] is 2) or (j+1 >= 0 and newGrid[i,j+1] is 2), then

            • grid[i, j] := 2

            • flag := true

          • freshLeft := true

    • if flag is non-zero, then −

      • (increase minutes by 1)

    • Otherwise

      • Come out from the loop

  • return (if freshLeft is not equal to true, then minutes, otherwise -1)

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int orangesRotting(vector<vector<int>> &grid) {
      int minutes = 0;
      int rowMax = grid.size();
      int colMax = grid[0].size();
      bool freshLeft = false;
      auto newGrid = grid;
      while (true) {
         newGrid = grid;
         bool flag = false;
         freshLeft = false;
         for (int i = 0; i < rowMax; i++) {
            for (int j = 0; j < colMax; j++) {
               if (newGrid[i][j] == 1) {
                  if ((i - 1 >= 0 && newGrid[i - 1][j] == 2) or (i + 1 < rowMax && newGrid[i + 1][j] == 2) or (j - 1 >= 0 && newGrid[i][j - 1] == 2) or (j + 1 < colMax && newGrid[i][j + 1] == 2)) {
                     grid[i][j] = 2;
                     flag = true;
                  }
                  freshLeft = true;
               }
            }
         }
         if (flag)
            minutes++;
         else
            break;
      }
      return (freshLeft != true) ? minutes : -1;
   }
};
main() {
   Solution ob;
   vector<vector<int>> v = {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}};
   cout << (ob.orangesRotting(v));
}

Input

{{2, 1, 1}, {1, 1, 0}, {0, 1, 1}}

Output

4
raja
Updated on 16-Nov-2020 13:48:11

Advertisements