Suppose we have one N x N grid, each square grid[i][j] represents the elevation at that point (i,j). Now consider it has started raining. At time t, the depth of the water everywhere is t. We can swim from a square to another 4-directionally adjacent square when elevation of both squares individually is at most t. We can swim infinite distance in zero time.
We should start from position (0, 0). We have to find the least time until we can reach the bottom right square (N-1, N-1)
So if the input is like
0 | 1 | 2 | 3 | 4 |
24 | 23 | 22 | 21 | 5 |
12 | 13 | 15 | 15 | 16 |
11 | 17 | 18 | 19 | 20 |
10 | 9 | 8 | 7 | 6 |
The correct way is colored. So the answer will be 16.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; struct Data{ int time, x, y; Data(int a, int b, int y){ time = a; x = b; this->y = y; } }; struct Comparator{ bool operator()(Data a, Data b){ return !(a.time < b.time); } }; int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1}}; class Solution { public: int swimInWater(vector<vector<int>>& grid) { int n = grid.size(); int m = grid[0].size(); priority_queue <Data, vector <Data>, Comparator> q; vector < vector <int> > visited(n, vector <int>(m, 0)); visited[0][0] = 1; q.push(Data(grid[0][0], 0, 0)); while(!q.empty()){ Data node = q.top(); q.pop(); int time = node.time; int x = node.x; int y = node.y; if(x == n - 1 && y == m - 1)return time; for(int i = 0; i < 4; i++){ int nx = dir[i][0] + x; int ny = dir[i][1] + y; if(nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny]){ visited[nx][y] = 1; q.push(Data(max(grid[nx][ny], time), nx, ny)); } } } return -1; } }; main(){ Solution ob; vector<vector<int>> v = {{0,1,2,3,4},{24,23,22,21,5},{12,13,15,15,16},{11,17,18,19,20}, {10,9,8,7,6}}; cout << (ob.swimInWater(v)); }
{{0,1,2,3,4},{24,23,22,21,5},{12,13,15,15,16},{11,17,18,19,20},{10,9,8,7,6}}
16