TC:O(n*mlog(n*m))
SC :O(n*m)
//BFS : dijkstra's
class Solution {
public int minimumObstacles(int[][] grid) {
int minObstacleRemoved = Integer.MAX_VALUE;
Queue<Cell> q = new PriorityQueue<>((a,b)-> Integer.compare(a.c,b.c));
int visited[][] = new int[grid.length][grid[0].length];
q.add(new Cell(0,0,0));
while(!q.isEmpty()){
Cell cell = q.remove();
int I = cell.i;
int J = cell.j;
if(visited[I][J] ==1) continue;
visited[I][J] = 1;
if(I == grid.length-1 && J == grid[0].length-1) {
minObstacleRemoved = cell.c;
break;
}
int dirs[][] = {{0,-1},{0,1},{-1,0},{1,0}};
int obstacleRemovedSoFar = cell.c;
for(int dir[]: dirs){
int i = I + dir[0];
int j = J + dir[1];
if(i>=0 && j>=0 && i<grid.length && j< grid[0].length && visited[i][j]==0){
int c = obstacleRemovedSoFar;
//if it is an obstacle then 1 more obstacle you will have to remove
if(grid[i][j]==1) c+=1;
q.add(new Cell(i,j,c));
}
}
}
return minObstacleRemoved;
}
}
class Cell{
int i;
int j;
int c;
public Cell(int i, int j, int c){
this.i = i;
this.j = j;
this.c = c;
}
}
Author Of article : Prashant Mishra Read full article