<p>You are given an <code>n x n</code> integer matrix <code>grid</code> where each value <code>grid[i][j]</code> represents the elevation at that point <code>(i, j)</code>.</p>

<p>The rain starts to fall. At time <code>t</code>, the depth of the water everywhere is <code>t</code>. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most <code>t</code>. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.</p>

<p>Return <em>the least time until you can reach the bottom right square </em><code>(n - 1, n - 1)</code><em> if you start at the top left square </em><code>(0, 0)</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/29/swim1-grid.jpg" style="width: 164px; height: 165px;" />
<pre>
<strong>Input:</strong> grid = [[0,2],[1,3]]
<strong>Output:</strong> 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/29/swim2-grid-1.jpg" style="width: 404px; height: 405px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The final route is shown.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= n &lt;= 50</code></li>
	<li><code>0 &lt;= grid[i][j] &lt;&nbsp;n<sup>2</sup></code></li>
	<li>Each value <code>grid[i][j]</code> is <strong>unique</strong>.</li>
</ul>

// class Solution {
// public:
//     int swimInWater(vector<vector<int>>& grid) {
//         int n = grid.size();
//         int vis[n][n];
//         memset(vis, 0, sizeof(vis));
//         priority_queue<pair<int, pair<int, int>>,
//                        vector<pair<int, pair<int, int>>>,
//                        greater<pair<int, pair<int, int>>>>
//             pq;

//         pq.push({grid[0][0], {0, 0}});
//         vis[0][0] = 1;
//         int max_time = 0;
//         while (!pq.empty()) {
//             auto it = pq.top();
//             int time = it.first;
//             int row = it.second.first;
//             int col = it.second.second;
//             pq.pop();
//              max_time = max(max_time,time);
//             if (row == n - 1 && col == n - 1)
//                 return max_time;

//             int dr[] = {-1, 1, 0, 0};
//             int dc[] = {0, 0, -1, 1};

//             for (int i = 0; i < 4; i++) {
//                 int newr = row + dr[i];
//                 int newc = col + dc[i];
//                 if (newr >= 0 && newc >= 0 && newr < n && newc < n &&
//                     !vis[newr][newc]) {

//                     vis[newr][newc] = 1;
//                     pq.push({grid[newr][newc], {newr, newc}});
//                 }
//             }
//         }
//         return 0;
//     }
// };
// class Disjointset
// {
// private:
//     vector<int> parent, size; // parent will store the parents '
//                               // size will be taken to rank or compare the parent order while doing union.
// public:
//     Disjointset(int n)
//     {
//         parent.resize(n + 1);
//         size.resize(n, 1);
//         for (int i = 0; i < n + 1; i++)
//         {
//             parent[i] = i; // element will be it's parent only
//         }
//     }
//     int find(int X)
//     {
//         if (parent[X] == X)
//             return X;

//         return parent[X] = find(parent[X]); // path compression
//     }
//     void UNION(int X, int Y)
//     {
//         int parent1 = find(X);
//         int parent2 = find(Y);
//         if (parent1 == parent2)
//             return; // CYCLE DETECTED.
//         if (size[parent1] < size[parent2])
//         {
//             parent[parent1] = parent2;
//             size[parent2] += size[parent1];
//         }
//         else
//         {
//             parent[parent2] = parent1;
//             size[parent1] += size[parent2];
//         }
//     }
//     void printArrays()
//     {
//         cout << "PARENT" << endl;
//         for (auto it : parent)
//         {
//             cout << it << " ";
//         }
//         cout << endl;
//         cout << "SIZE" << endl;
//         for (auto it : size)
//         {
//             cout << it << " ";
//         }
//     }
//     int SIZE(int vertex) // returns the size of the whole disjoint set of which the current vertex is a part of.
//     {
//         return size[find(vertex)]; // returns the size of disjoint set that it is a part of.
//     }

//     int noOfdisjointSets(int n) // pass n as indexing. , gives all disjoint sets and not particular
//     {
//         // find the parent of all nodes.

//         for (int i = 0; i < n; i++)
//         {
//             parent[i] = find(i);
//         }

//         int cnt = 0;
//         for (int i = 0; i < n; i++)
//         {
//             if (parent[i] == i)
//             {
//                 cnt++;
//             }
//         }
//         return cnt;

//         /*
//       //   METHOD 2
//         set<int> s;
//         for(int i=0;i<n;i++)
//         {
//             s.insert(parent[i]);
//         }
//         return s.size();
//         */
//     }
// };

// class Solution
// {
// public:
//     int swimInWater(vector<vector<int>> &grid)
//     {
//         return UnionAndFind_swimInWater(grid);
//     }
//     int UnionAndFind_swimInWater(vector<vector<int>> &grid)
//     {
//         int n = grid.size();
//         Disjointset ds(n * n);
//         pair<int, int> locations[n * n];                // store the location of the element reachable exactly at time t.
//         vector<vector<int>> vis(n, vector<int>(n, -1)); // can use grid for this purpose also.
//         for (int i = 0; i < n; i++)                     // storing the locations of elements
//         {
//             for (int j = 0; j < n; j++)
//             {
//                 locations[grid[i][j]] = {i, j};
//             }
//         }

//         int delRow[] = {0, 0, 1, -1};
//         int delCol[] = {1, -1, 0, 0};
//         // now the time will be in range from 0 to n*n -1
//         for (int time = 0; time < n * n; time++)
//         {

//             // find the loc of element reachable exactly at  this time {x,y}
//             int x = locations[time].first;
//             int y = locations[time].second;
          
//             // mark the current as visited
//             vis[x][y] = 1;
//             // check if all it's neighbours, if they have already been reached then merge with it.
//             for (int k = 0; k < 4; k++)
//             {
//                 int nrow = x + delRow[k];
//                 int ncol = y + delCol[k];
//                 if (underBoundaries(nrow, ncol, n, n) && vis[nrow][ncol] == 1)
//                 {
//                     ds.UNION(x*n+y,nrow*n+ncol);//join the locations here and not the heights.
//                 }
//             }
//             if (ds.find(0) == ds.find(n*n-1)) // if last element location in the connected component
//             {
//                 return time;
//             }
//         }

//         return n * n - 1; // since in max time it will be possible to reach the desired
//         // the code will itself cover this situation and does not require it here only.
//         /*
//          some intutive improvements in the problem:
//           since time is increasing linearly,
//           so any element which has lesser value than current time is already visited
//           so we can say element<time then already visited.
//           we can save ourselves of vis extra n square space.
//         */
//     }
//     bool underBoundaries(int nrow, int ncol, int n, int m)
//     {
//         if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m)
//         {
//             return true;
//         }
//         return false;
//     }
// };

class Solution {
    int n;
    
    bool dfs(vector<vector<int>>& grid, int i, int j, int T, vector<vector<bool>>& visited) {
        if (i < 0 || i >= n || j < 0 || j >= n || visited[i][j] || grid[i][j] > T) return false;
        visited[i][j] = true;
        if (i == n - 1 && j == n - 1) return true;
        
        return dfs(grid, i - 1, j, T, visited) || 
               dfs(grid, i + 1, j, T, visited) || 
               dfs(grid, i, j - 1, T, visited) || 
               dfs(grid, i, j + 1, T, visited);
    }

public:
    int swimInWater(vector<vector<int>>& grid) {
        this->n = grid.size();
        int l = grid[0][0], r = n * n - 1;
        
        while (l < r) {
            int m = l + ((r - l) >> 1);
            vector<vector<bool>> visited(n, vector<bool>(n, false));
            
            if (dfs(grid, 0, 0, m, visited)) {
                r = m;
            } else {
                l = m + 1;
            }
        }
        
        return l;
    }
};

12106