Re: [閒聊] 每日leetcode
3341. Find Minimum Time to Reach Last Room I
給你一個二維陣列表示前往每個房間時,需要在哪個時間點以後,求出從(0,0)到(n-1,m-1
)最早是哪個時間點,每次房間之間移動要消耗一個時間單位。
思路:
1.找最短路徑 所以用BFS 我快睡著了 隨便亂寫要去躺床了 姆咪。
Java Code:
------------------------------------------
class Solution {
private int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int minTimeToReach(int[][] moveTime) {
int n = moveTime.length;
int m = moveTime[0].length;
int[][] dis = new int[n][m];
for (int[] row : dis) {
Arrays.fill(row, Integer.MAX_VALUE);
}
dis[0][0] = 0;
PriorityQueue<int[]> pq = new
PriorityQueue<>(Comparator.comparingInt(a -> a[2]));
pq.add(new int[]{0, 0, 0});
while (!pq.isEmpty()) {
int[] p = pq.poll();
int y = p[0];
int x = p[1];
int d = p[2];
for (int[] dir : dirs) {
int newY = y + dir[0];
int newX = x + dir[1];
if (newY < 0 || newX < 0 || newY >= n || newX >= m) {
continue;
}
int nextD;
if (moveTime[newY][newX] > d) {
nextD = moveTime[newY][newX] + 1;
} else {
nextD = d + 1;
}
if (nextD >= dis[newY][newX]) {
continue;
}
dis[newY][newX] = nextD;
pq.add(new int[]{newY, newX, nextD});
}
}
return dis[n - 1][m - 1];
}
}
------------------------------------------
--
https://i.imgur.com/9FXhO25.jpeg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.104.111 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1746640390.A.56F.html
討論串 (同標題文章)
完整討論串 (本文為第 1420 之 1548 篇):