LeetCode 3342.到达最后一个房间的最少时间 II:dijkstra算法(和I一样)
【LetMeFly】3342.到达最后一个房间的最少时间 II:dijkstra算法(和I一样)
力扣题目链接:https://leetcode.cn/problems/find-minimum-time-to-reach-last-room-ii/
有一个地窖,地窖中有 n x m
个房间,它们呈网格状排布。
给你一个大小为 n x m
的二维数组 moveTime
,其中 moveTime[i][j]
表示在这个时刻 以后 你才可以 开始 往这个房间 移动 。你在时刻 t = 0
时从房间 (0, 0)
出发,每次可以移动到 相邻 的一个房间。在 相邻 房间之间移动需要的时间为:第一次花费 1 秒,第二次花费 2 秒,第三次花费 1 秒,第四次花费 2 秒……如此 往复 。
请你返回到达房间 (n - 1, m - 1)
所需要的 最少 时间。
如果两个房间有一条公共边(可以是水平的也可以是竖直的),那么我们称这两个房间是 相邻 的。
示例 1:
输入:moveTime = [[0,4],[4,4]]
输出:7
解释:
需要花费的最少时间为 7 秒。
- 在时刻
t == 4
,从房间(0, 0)
移动到房间(1, 0)
,花费 1 秒。 - 在时刻
t == 5
,从房间(1, 0)
移动到房间(1, 1)
,花费 2 秒。
示例 2:
输入:moveTime = [[0,0,0,0],[0,0,0,0]]
输出:6
解释:
需要花费的最少时间为 6 秒。
- 在时刻
t == 0
,从房间(0, 0)
移动到房间(1, 0)
,花费 1 秒。 - 在时刻
t == 1
,从房间(1, 0)
移动到房间(1, 1)
,花费 2 秒。 - 在时刻
t == 3
,从房间(1, 1)
移动到房间(1, 2)
,花费 1 秒。 - 在时刻
t == 4
,从房间(1, 2)
移动到房间(1, 3)
,花费 2 秒。
示例 3:
输入:moveTime = [[0,1],[1,2]]
输出:4
提示:
2 <= n == moveTime.length <= 750
2 <= m == moveTime[i].length <= 750
0 <= moveTime[i][j] <= 109
解题方法:dijkstra算法
如果你看过了最少时间 I,那么可以直接跳过下面引用部分:
使用一个数组记录每个位置的最早到达时间(初始值除了起点为0外全是“正无穷”)。
使用一个优先队列将所有访问到的节点入队,首次访问时间最早的节点最优先。初始时将起点入队。
接着在队列非空时不断将节点出队(若已有比出队节点访问时间更早的解法则continue),判断节点的4个相邻节点,若相邻节点能更早访问则入队。
本题与上题的不同之处在于,本题访问相邻房间的耗时是不固定的。耗时为多少呢?不难发现,如果起点下标为 ( x , y ) (x, y) (x,y),那么移动耗时为 1 + ( x + y ) m o d 2 1+(x+y)\mod 2 1+(x+y)mod2
- 时间复杂度 O ( n m log ( n m ) ) O(nm\log (nm)) O(nmlog(nm)),其中 n × m = s i z e ( m o v e T i m e ) n\times m=size(moveTime) n×m=size(moveTime),每个节点最多作为起点一次(每次出队节点的时间总是非递减的)。
- 空间复杂度 O ( n m ) O(nm) O(nm)
AC代码
C++
/** @Author: LetMeFly* @Date: 2025-05-09 12:45:04* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-05-09 13:17:17*/
class Solution {
private:static constexpr int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public:int minTimeToReach(vector<vector<int>>& moveTime) {int n = moveTime.size(), m = moveTime[0].size();vector<vector<int>> ans(n, vector<int>(m, 2000000001));ans[0][0] = 0;priority_queue<tuple<int, int, int>> pq;pq.push({0, 0, 0});while (pq.size()) {auto [t, x, y] = pq.top();pq.pop();t = -t;if (t > ans[x][y]) {continue;}for (int d = 0; d < 4; d++) {int nx = x + directions[d][0];int ny = y + directions[d][1];if (nx < 0 || nx >= n || ny < 0 || ny >= m) {continue;}int nt = max(t, moveTime[nx][ny]) + (x + y) % 2 + 1;if (nt < ans[nx][ny]) {ans[nx][ny] = nt;pq.push({-nt, nx, ny});}}}return ans[n - 1][m - 1];}
};
Python
'''
Author: LetMeFly
Date: 2025-05-09 12:45:04
LastEditors: LetMeFly.xyz
LastEditTime: 2025-05-09 13:38:28
'''
from typing import List
import heapqDIRECTIONS = [[0, 1], [0, -1], [-1, 0], [1, 0]]class Solution:def minTimeToReach(self, moveTime: List[List[int]]) -> int:n, m = len(moveTime), len(moveTime[0])ans = [[2000000001] * m for _ in range(n)]ans[0][0] = 0pq = [(0, 0, 0)]while pq:t, x, y = heapq.heappop(pq)if t > ans[x][y]:continuefor dx, dy in DIRECTIONS:nx = x + dxny = y + dyif not (0 <= nx < n and 0 <= ny < m):continuent = max(t, moveTime[nx][ny]) + (x + y) % 2 + 1if nt < ans[nx][ny]:ans[nx][ny] = ntheapq.heappush(pq, (nt, nx, ny))return ans[n - 1][m - 1]
Java
/** @Author: LetMeFly* @Date: 2025-05-09 12:45:04* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-05-09 13:48:19*/
import java.util.PriorityQueue;
import java.util.Arrays;class Solution {private static final int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};public int minTimeToReach(int[][] moveTime) {int n = moveTime.length, m = moveTime[0].length;int[][] ans = new int[n][m];for (int i = 0; i < n; i++) {Arrays.fill(ans[i], 2000000001);}ans[0][0] = 0;PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);pq.offer(new int[]{0, 0, 0});while (!pq.isEmpty()) {int[] node = pq.poll();int t = node[0], x = node[1], y = node[2];if (t > ans[x][y]) {continue;}for (int[] d : directions) {int nx = x + d[0];int ny = y + d[1];if (nx < 0 || nx >= n || ny < 0 || ny >= m) {continue;}int nt = Math.max(t, moveTime[nx][ny]) + (x + y) % 2 + 1;if (nt < ans[nx][ny]) {ans[nx][ny] = nt;pq.offer(new int[]{nt, nx, ny});}}}return ans[n - 1][m - 1];}
}
Go
/** @Author: LetMeFly* @Date: 2025-05-09 12:45:04* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-05-09 18:58:00*/
package mainimport "container/heap"var directions3342 [][]int = [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}func minTimeToReach(moveTime [][]int) int {n, m := len(moveTime), len(moveTime[0])ans := make([][]int, n)for i := range ans {ans[i] = make([]int, m)for j := range ans[i] {ans[i][j] = 2000000001}}ans[0][0] = 0pq := &pq3342{}heap.Init(pq)heap.Push(pq, node3342{0, 0, 0})for len(*pq) > 0 {node := heap.Pop(pq).(node3342)t, x, y := node.t, node.x, node.yif t > ans[x][y] {continue}for _, d := range directions3342 {nx := x + d[0]ny := y + d[1]if nx < 0 || nx >= n || ny < 0 || ny >= m {continue}nt := max(t, moveTime[nx][ny]) + (x + y) % 2 + 1if nt < ans[nx][ny] {ans[nx][ny] = ntheap.Push(pq, node3342{nt, nx, ny})}}}return ans[n - 1][m - 1]
}type node3342 struct {t, x, y int
}type pq3342 []node3342func (pq pq3342) Len() int {return len(pq)}
func (pq pq3342) Swap(i, j int) {pq[i], pq[j] = pq[j], pq[i]}
func (pq pq3342) Less(i, j int) bool {return pq[i].t < pq[j].t}
func (pq *pq3342) Pop() (ans any) {*pq, ans = (*pq)[:len(*pq)-1], (*pq)[len(*pq)-1]; return}
func (pq *pq3342) Push(node any) {*pq = append(*pq, node.(node3342))}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源