|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int n; |
| 4 | + // Check if coordinates are valid within the grid boundaries |
| 5 | + bool valid(int i, int j) { |
| 6 | + return (i >= 0 && i < n && j >= 0 && j < n); |
| 7 | + } |
| 8 | + // Check if coordinates are valid within the grid boundaries |
| 9 | + bool isValid(int x, int y, int n) { |
| 10 | + return x >= 0 && x < n && y >= 0 && y < n; |
| 11 | + } |
| 12 | + |
| 13 | + // Function to compute the minimum distance grid |
| 14 | + vector<vector<int>> computeDistanceGrid(vector<vector<int>>& grid) { |
| 15 | + int n = grid.size(); |
| 16 | + vector<vector<int>> distGrid(n, vector<int>(n, INT_MAX)); // Initialize with maximum value |
| 17 | + queue<pair<int, int>> q; |
| 18 | + |
| 19 | + // Initialize the queue and distance for '0' cells |
| 20 | + for (int i = 0; i < n; ++i) { |
| 21 | + for (int j = 0; j < n; ++j) { |
| 22 | + if (grid[i][j] == 1) { |
| 23 | + q.push({i, j}); |
| 24 | + distGrid[i][j] = 0; |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // Directions: up, down, left, right |
| 30 | + vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; |
| 31 | + |
| 32 | + // BFS to compute minimum distances |
| 33 | + while (!q.empty()) { |
| 34 | + auto [x, y] = q.front(); |
| 35 | + q.pop(); |
| 36 | + for (auto& dir : directions) { |
| 37 | + int newX = x + dir.first; |
| 38 | + int newY = y + dir.second; |
| 39 | + if (isValid(newX, newY, n) && distGrid[newX][newY] == INT_MAX) { |
| 40 | + distGrid[newX][newY] = distGrid[x][y] + 1; |
| 41 | + q.push({newX, newY}); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return distGrid; |
| 47 | + } |
| 48 | + |
| 49 | + int maximumSafenessFactor(vector<vector<int>>& grid) { |
| 50 | + n = grid.size(); |
| 51 | + if (grid[n - 1][n - 1] == 1 || grid[0][0] == 1) return 0; |
| 52 | + |
| 53 | + vector<vector<int>> dist = computeDistanceGrid(grid); |
| 54 | + priority_queue<pair<int, pair<int, int>>> pq; |
| 55 | + vector<vector<int>> vis(n, vector<int>(n, 0)); |
| 56 | + |
| 57 | + vector<int> delr = {-1, 0, 1, 0}; |
| 58 | + vector<int> delc = {0, 1, 0, -1}; |
| 59 | + |
| 60 | + pq.push({dist[0][0], {0, 0}}); |
| 61 | + vis[0][0] = 1; |
| 62 | + |
| 63 | + while (!pq.empty()) { |
| 64 | + auto it = pq.top(); |
| 65 | + pq.pop(); |
| 66 | + int ds = it.first; |
| 67 | + int i = it.second.first; |
| 68 | + int j = it.second.second; |
| 69 | + |
| 70 | + if (i == n - 1 && j == n - 1) return ds; |
| 71 | + |
| 72 | + for (int l = 0; l < 4; ++l) { |
| 73 | + int nrow = i + delr[l]; |
| 74 | + int ncol = j + delc[l]; |
| 75 | + if (valid(nrow, ncol) && grid[nrow][ncol] != 1 && !vis[nrow][ncol]) { |
| 76 | + vis[nrow][ncol] = 1; |
| 77 | + int ds1 = dist[nrow][ncol]; |
| 78 | + pq.push({min(ds, ds1), {nrow, ncol}}); |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + return 0; |
| 84 | + } |
| 85 | +}; |
0 commit comments