#3342
Find Minimum Time to Reach Last Room II
MediumArrayGraph TheoryHeap (Priority Queue)MatrixShortest PathDijkstra's AlgorithmGraph TraversalPriority Queue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a priority queue (min-heap) to implement Dijkstra's algorithm, which efficiently finds the shortest path in a weighted grid. Each state considers the current room, the time taken to reach it, and whether the last move was odd or even.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a priority queue with the starting room (0, 0) and the initial time.
- 2Step 2: While the queue is not empty, extract the room with the minimum time.
- 3Step 3: For each adjacent room, calculate the new time based on whether the last move was odd or even, and push the new state into the queue if it improves the time.
solution.py19 lines
1import heapq
2
3def minTime(moveTime):
4 n, m = len(moveTime), len(moveTime[0])
5 pq = [(moveTime[0][0], 0, 0, True)] # (time, x, y, odd)
6 visited = set()
7 while pq:
8 time, x, y, odd = heapq.heappop(pq)
9 if (x, y) == (n - 1, m - 1):
10 return time
11 if (x, y, odd) in visited:
12 continue
13 visited.add((x, y, odd))
14 for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
15 nx, ny = x + dx, y + dy
16 if 0 <= nx < n and 0 <= ny < m:
17 next_time = time + (1 if odd else 2) + moveTime[nx][ny]
18 heapq.heappush(pq, (next_time, nx, ny, not odd))
19 return -1ℹ
Complexity note: The time complexity is O(n log n) because we are using a priority queue to process each room efficiently. The space complexity is O(n) due to the storage of visited states and the priority queue.
- 1Understanding the alternating move times is crucial for calculating the total time.
- 2Using a priority queue allows us to efficiently find the shortest path.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.