|
| 1 | +/*--------------------------------------- |
| 2 | + Time Complexity: O(m * n * log(m * n)) |
| 3 | + Space Complexity: O(m * n) |
| 4 | +------------------------------------------*/ |
| 5 | + |
| 6 | +class Solution { |
| 7 | +public: |
| 8 | + int maximumSafenessFactor(vector<vector<int>>& grid) { |
| 9 | + int n = grid.size(); |
| 10 | + int m = grid[0].size(); |
| 11 | + vector<vector<int>> safenessFactor(n, vector<int> (m, 1e9)); |
| 12 | + queue<pair<int, int>> fifo; |
| 13 | + |
| 14 | + for(int i = 0; i <= n - 1; i++){ |
| 15 | + for(int j = 0; j <= m - 1; j++){ |
| 16 | + if(grid[i][j] == 1){ |
| 17 | + safenessFactor[i][j] = 0; |
| 18 | + fifo.push({i, j}); |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + while(!fifo.empty()){ |
| 24 | + auto [i, j] = fifo.front(); |
| 25 | + fifo.pop(); |
| 26 | + |
| 27 | + vector<pair<int, int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; |
| 28 | + for(auto dir : directions){ |
| 29 | + int newX = i + dir.first; |
| 30 | + int newY = j + dir.second; |
| 31 | + |
| 32 | + if(newX >= 0 && newY >= 0 && newX < n && newY < m && safenessFactor[newX][newY] > 1 + safenessFactor[i][j]){ |
| 33 | + safenessFactor[newX][newY] = 1 + safenessFactor[i][j]; |
| 34 | + fifo.push({newX, newY}); |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + priority_queue<pair<int, pair<int, int>>> maxHeap; |
| 40 | + vector<vector<bool>> visited(n, vector<bool>(m, false)); |
| 41 | + maxHeap.push({safenessFactor[0][0], {0, 0}}); |
| 42 | + visited[0][0] = true; |
| 43 | + while(!maxHeap.empty()){ |
| 44 | + auto [safeness, temp] = maxHeap.top(); |
| 45 | + auto [i, j] = temp; |
| 46 | + maxHeap.pop(); |
| 47 | + |
| 48 | + if(i == n - 1 && j == m - 1) return safeness; |
| 49 | + |
| 50 | + vector<pair<int, int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; |
| 51 | + for(auto dir : directions){ |
| 52 | + int newX = i + dir.first; |
| 53 | + int newY = j + dir.second; |
| 54 | + |
| 55 | + if(newX >= 0 && newY >= 0 && newX < n && newY < m && !visited[newX][newY]){ |
| 56 | + int currSafe = min(safeness, safenessFactor[newX][newY]); |
| 57 | + maxHeap.push({currSafe, {newX, newY}}); |
| 58 | + visited[newX][newY] = true; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + return 0; |
| 63 | + } |
| 64 | +}; |
| 65 | + |
| 66 | +/* |
| 67 | +Question Link: https://leetcode.com/problems/find-the-safest-path-in-a-grid/ |
| 68 | +Author: M.R.Naganathan |
| 69 | +*/ |
0 commit comments