RottenOranges
Anonymous User
155

'''
#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
int changedCount;
bool changed;
void change(int r, int c, vector<vector> &grid) {
if (grid[r][c] == 1) {
grid[r][c] = 2;
changed = true;
}
}

int orangesRotting(vector<vector<int>> &grid) {

    std::vector<vector<int>> snapshot;
    int changedCount = 0;
   bool changed = false;
        // Deep copy for the next comparison.
        snapshot = grid;

        int r = 0, c = 0;
        for (vector<int> rows : snapshot) {
           // c = 0;
            for (int el : rows) {
                if (el == 2) {
                    if (grid[r-1][c]==1)
                        grid[r-1][c] == 2;
                        change(r - 1, c, grid);
                  //  if (c < grid.at(0).size() - 1)
                  if (grid[r][c+1] == 1)
                        grid[r][c+1] == 2;
                        change(r, c + 1, grid);
                    //if (r < grid.size() - 1)
                    if (grid[r+1][c] == 1)
                        grid[r+1][c] == 2;
                        change(r + 1, c, grid);
                    //if (c > 0)
                    if (grid[r][c-1] == 1)
                    grid[r][c-1] == 2;
                        change(r, c - 1, grid);
                }
                c++;
            }
            r++;
        }
        if (changed)
            changedCount++;
   
    // Find an orange that is never rotten and returns -1 if found.
    for (auto rows : grid) {
        for (auto el : rows) {
            if (el == 1)
                return -1;
        }
    }

    return changedCount;
}

};

int main()
{
//int r=0, c=0;
Solution::change(vector<vector> grid){ {2, 1, 0, 2, 1},
{1, 0, 1, 2, 1},
{1, 0, 0, 2, 1}};
int changedCount = orangesRotting(grid);
if (changedCount == -1)
cout << "All oranges cannot rotn";
else
cout << "Time required for all oranges to rot => " << changedCount << endl;
return 0;
}

Comments (2)