fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. /*
  6. You are given an m x n grid where each cell can have one of three values:
  7.  
  8. 0 representing an empty cell,
  9. 1 representing a fresh orange, or
  10. 2 representing a rotten orange.
  11. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
  12.  
  13. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
  14. */
  15.  
  16.  
  17. int minutes(vector<vector<int>>& grid) {
  18. int m = grid.size();
  19. int n = grid[0].size();
  20. int fo = 0, temp; // fresh oranges
  21.  
  22. vector<vector<int>> visited = grid;
  23. queue<pair<int,int>> qq;
  24.  
  25. for (int i=0;i<m;i++) {
  26. for (int j=0;j<n;j++) {
  27. if (visited[i][j]==2)
  28. qq.push({i, j});
  29. if (visited[i][j]==1)
  30. fo++;
  31. }
  32. }
  33.  
  34. if (fo==0) return 0; // no fresh oranges
  35. if (qq.empty()) return -1; // no rotten oranges
  36.  
  37. int ans = -1;
  38. vector<vector<int>> dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}};
  39. while (!qq.empty()) {
  40. temp = qq.size();
  41. while (temp--) {
  42. auto [x,y] = qq.front();
  43. qq.pop();
  44. for (auto it: dirs) {
  45. int i = x+it[0];
  46. int j = y+it[1];
  47. if (i>=0 && i<m && j>=0 && j<n && visited[i][j]==1) {
  48. visited[i][j] = 2;
  49. fo--;
  50. qq.push({i,j});
  51. }
  52. }
  53. }
  54. ans++;
  55. }
  56.  
  57. if (fo!=0) return -1;
  58. else return ans;
  59.  
  60. }
  61.  
  62.  
  63. int main() {
  64. cout<<"Hello World!\n";
  65. vector<vector<int>> grid = {
  66. {0,0,0},
  67. {0,0,0},
  68. {0,0,0},
  69. };
  70. cout<<minutes(grid);
  71. }
  72.  
Success #stdin #stdout 0s 5320KB
stdin
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
stdout
Hello World!
0