PNB Coding logoPNB Coding

Daily LeetCode Solution - Code Share

778. Swim in Rising Water

class Solution {
public:
    int n;
    //helper function to tell if a cell is inside the matrix
    bool inside(int nextX, int nextY){
        return nextX >= 0 && nextX < n && nextY >= 0 && nextY < n;
    }

    int swimInWater(vector<vector<int>>& grid) {
        n = grid.size();
        priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq;
        pq.push({grid[0][0], 0, 0});

        vector<vector<bool>> visited(n, vector<bool>(n));
        visited[0][0] = true;

        int maxTillNow = 0;
        
        //helper vector to go through all neighbours
        vector<pair<int,int>> directions = {{0,1}, {1,0}, {0,-1}, {-1,0}};

        while(!pq.empty()){
            int level = pq.top()[0]; //always chose to expand to the lowest point
            int x = pq.top()[1];
            int y = pq.top()[2];
            pq.pop();

            maxTillNow = max(maxTillNow, level); //update the max level visited

            if(x == (n-1) && y == (n-1)){
                return maxTillNow; //arrived
            }
            
            for(auto& d : directions){
                int nextX = x + d.first;
                int nextY = y + d.second;
                if(!inside(nextX, nextY) || visited[nextX][nextY]) continue;
                visited[nextX][nextY] = true;
                pq.push({grid[nextX][nextY], nextX, nextY});
            }
        }
        return 0;
    }
};
Explore Courses1‑on‑1 Mentorship