Skip to content

Commit 96a5d01

Browse files
authored
Create Find Minimum Time to Reach Last Room I.java
1 parent f37ed97 commit 96a5d01

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
3+
private static final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
4+
5+
public int minTimeToReach(int[][] moveTime) {
6+
int n = moveTime.length;
7+
int m = moveTime[0].length;
8+
boolean[][] visited = new boolean[n][m];
9+
Integer[][] minTime = new Integer[n][m];
10+
minTime[0][0] = 0;
11+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]);
12+
pq.add(new int[]{0, 0, 0});
13+
while (!pq.isEmpty()) {
14+
int[] removed = pq.remove();
15+
int x = removed[0];
16+
int y = removed[1];
17+
if (visited[x][y]) {
18+
continue;
19+
}
20+
visited[x][y] = true;
21+
for (int[] dir : DIRS) {
22+
int newX = x + dir[0];
23+
int newY = y + dir[1];
24+
if (newX >= 0 && newY >= 0 && newX < n && newY < m) {
25+
int distance = Math.max(minTime[x][y], moveTime[newX][newY]) + 1;
26+
int currMinTime = minTime[newX][newY] == null ? Integer.MAX_VALUE : minTime[newX][newY];
27+
if (currMinTime > distance) {
28+
minTime[newX][newY] = distance;
29+
pq.add(new int[]{newX, newY, distance});
30+
}
31+
}
32+
}
33+
}
34+
return minTime[n - 1][m - 1];
35+
}
36+
}

0 commit comments

Comments
 (0)