From b6331f6edd1f93852a1e7e6ddc6416dd894880f5 Mon Sep 17 00:00:00 2001 From: Fazeel Usmani Date: Fri, 29 Oct 2021 22:11:44 +0530 Subject: [PATCH] Create 29_rottingOranges.cpp --- .../29_rottingOranges.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 10 October LeetCode Challenge 2021/29_rottingOranges.cpp diff --git a/10 October LeetCode Challenge 2021/29_rottingOranges.cpp b/10 October LeetCode Challenge 2021/29_rottingOranges.cpp new file mode 100644 index 0000000..f7b262c --- /dev/null +++ b/10 October LeetCode Challenge 2021/29_rottingOranges.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + int orangesRotting(vector>& grid) { + + if (grid.empty() || grid[0].empty()) + return 0; + + int H = grid.size(); + int W = grid[0].size(); + + auto inside = [&](int row, int col){ + return 0<=row && row > q; + + for (int i = 0; i < H; ++i){ + for (int j = 0; j < W; ++j){ + if (grid[i][j] == 2){ + q.push({i, j}); + } + } + } + + vector > directions { {-1,0}, {0,-1}, {1,0}, {0,1} }; + int minutes = 0; + + while (!q.empty()){ + + int sz = q.size(); + bool flag = false; + for (int k=0; k orange = q.front(); + q.pop(); + int i = orange.first, j = orange.second; + + for (pair dir: directions){ + int newRow = i + dir.first; + int newCol = j + dir.second; + if (inside(newRow,newCol) && grid[newRow][newCol] == 1){ + flag = true; + q.push({newRow, newCol}); + grid[newRow][newCol] = 2; + } + } + } + if (flag) + minutes++; + } + + for(auto rows : grid) + for(auto val : rows) + if(val == 1) + return -1; + + return minutes; + } +};