Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chrisynchen/68591760c95ca595560ba2b0641f59c8 to your computer and use it in GitHub Desktop.
Save chrisynchen/68591760c95ca595560ba2b0641f59c8 to your computer and use it in GitHub Desktop.
2290. Minimum Obstacle Removal to Reach Corner
//dijkstra TLE
public int minimumObstacles(int[][] grid) {
//dijkstra
int[][] ref = new int[][]{{-1,0}, {1,0}, {0,-1}, {0,1}};
int[][] minDistance = new int[grid.length][grid[0].length];
for(int[] e: minDistance) {
Arrays.fill(e, Integer.MAX_VALUE);
}
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> {
if(a[2] == b[2]) {
return b[3] - a[3];
} else {
return a[2] - b[2];
}
});
pq.offer(new int[]{0, 0, 0, 0});
while(!pq.isEmpty()) {
int[] current = pq.poll();
if(current[3] > minDistance[current[0]][current[1]]) continue;
for(int[] r: ref) {
int nextI = r[0] + current[0];
int nextJ = r[1] + current[1];
if(nextI == grid.length - 1 && nextJ == grid[0].length - 1) return current[2];
if(nextI < 0 || nextI >= grid.length || nextJ < 0 || nextJ >= grid[0].length || current[3] + 1 >= minDistance[nextI][nextJ]) continue;
minDistance[nextI][nextJ] = current[3] + 1;
pq.offer(new int[]{nextI, nextJ, current[2] + grid[nextI][nextJ], minDistance[nextI][nextJ]});
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment