DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Safest walk through the grid

Problem

TC : O(n*mlog(n*m))
SC: O(n*m)

//BFS approach (dijkstra's algorithm) class Triple{ int i; int j ; int h; public Triple(int i, int j, int h){ this.i =i; this.j = j; this.h =h; } } class Solution { public boolean findSafeWalk(List<List<Integer>> grid, int health) { int visited[][] = new int[grid.size()][grid.get(0).size()]; Queue<Triple> q = new PriorityQueue<>((a,b)->b.h-a.h); q.add(new Triple(0,0,health-grid.get(0).get(0))); while(!q.isEmpty()){ Triple t = q.remove(); if(t.i ==grid.size()-1 && t.j == grid.get(0).size()-1) return true; if(visited[t.i][t.j]==1) continue; visited[t.i][t.j] = 1; int dirs[][] = {{0,-1},{0,1},{-1,0},{1,0}}; for(int dir[] : dirs){ int x = t.i+dir[0]; int y = t.j+dir[1]; if(x>=0 && y>=0 && x<grid.size() && y<grid.get(0).size() && visited[x][y]==0 && t.h-grid.get(x).get(y)>0){ q.add(new Triple(x,y,t.h-grid.get(x).get(y))); } } } return false; } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)