Swim in rising water
Prashant Mishra

Prashant Mishra @prashantrmishra

About: There is always a price for those who persevere.

Location:
India
Joined:
Jul 2, 2022

Swim in rising water

Publish Date: Jul 12
0 0

Problem

class Solution {
    public int swimInWater(int[][] grid) {
        Queue<Data> q = new PriorityQueue<>((a,b)-> Integer.compare(a.t, b.t));
        q.add(new Data(0,0,grid[0][0]));
        int dirs[][] = {{0,1},{1,0},{0,-1},{-1,0}};
        int visited[][] = new int[grid.length][grid[0].length];
        while(!q.isEmpty()){
            Data d = q.remove();
            if(d.i == grid.length-1 && d.j == grid[0].length-1) {
                return d.t;
            }
            for(int dir[] : dirs){
                int i = dir[0] + d.i;
                int j = dir[1] + d.j;
                if(i>=0 && i< grid.length && j>=0 && j<grid[0].length && visited[i][j]==0 ){
                    visited[i][j] = 1;
                    q.add(new Data(i,j, Math.max(d.t, grid[i][j])));
                }
            }
        }
        return -1;
    }
}
class Data{
    int i;
    int j;
    int t;
    public Data(int i, int j, int t){
        this.i  =i;
        this.j = j;
        this.t = t;
    }
}


Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment