to determine what is the minimum time required to rot all oranges |
Given a matrix of dimension r*c where each cell in the matrix can have values 0, 1, or 2 which has the following meaning:
0: Empty cell
1: Cells have fresh oranges
2: Cells have rotten oranges
So, we have to determine what is the minimum time required to rot all oranges. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right) in unit time. If it is impossible to rot every orange then simply return -1.
Here is a simple and easy solution using queue with execution time is 0.06s.
#include <bits/stdc++.h> using namespace std; int solveRotten(vector < vector < int > > a, int n, int m) { int timer = -1; queue < pair < int, int > > q; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (a[i][j] == 2) { q.push(make_pair(i, j)); } } } while (!q.empty()) { int siz = q.size(); for (int i = 0; i < siz; ++i) { pair < int, int > p = q.front(); int j = p.first, k = p.second; if (j - 1 >= 0 && a[j - 1][k] == 1) { q.push(make_pair(j - 1, k)); a[j - 1][k] = 2; } if (j + 1 < n && a[j + 1][k] == 1) { q.push(make_pair(j + 1, k)); a[j + 1][k] = 2; } if (k - 1 >= 0 && a[j][k - 1] == 1) { q.push(make_pair(j, k - 1)); a[j][k - 1] = 2; } if (k + 1 < m && a[j][k + 1] == 1) { q.push(make_pair(j, k + 1)); a[j][k + 1] = 2; } q.pop(); } ++timer; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (a[i][j] == 1) { return -1; } } } return timer; } int main() { //code int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector < vector < int > > a(n, vector < int > (m, 0)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; } } cout << solveRotten(a, n, m) << endl; } return 0; }