Problem
There is a dungeon with n x m rooms arranged as a grid.
You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum time in seconds when you can start moving to that room. You start from the room (0, 0) at time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes exactly one second.
Return the minimum time to reach the room (n - 1, m - 1).
Two rooms are adjacent if they share a common wall, either horizontally or vertically.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Constraints:
2 <= n == moveTime.length <= 502 <= m == moveTime[i].length <= 500 <= moveTime[i][j] <= 10^9
Solution
Method 1 - Using Dijkstra’s algorithm
We need to find the minimum time required to reach the destination room (n-1, m-1) starting from (0, 0). This is an optimisation problem where we evaluate paths while adhering to the condition that each room has its own restriction defined by moveTime[i][j]. A room can only be entered after its restriction time has elapsed.
The grid can be seen as a graph, and moving between rooms represents edges. Using a priority queue (min-heap) is ideal for this task because we attempt to explore rooms with the smallest valid entry time first.
Approach
Initialisation:
- Using Dijkstra’s-like algorithm, maintain a priority queue to store the current position
(x, y)and the time required to enter that room. - Create a 2D array
visitedto ensure we don’t revisit rooms unnecessarily.
- Using Dijkstra’s-like algorithm, maintain a priority queue to store the current position
Algorithm:
- Push the starting room
(0, 0)into the priority queue with time0. - For each position in the queue, evaluate its adjacent rooms (
top,bottom,left,right). - For every adjacent room, calculate the time to move to that room and ensure it meets the
moveTimeconstraint. - Update the queue with the calculated valid time only if the room hasn’t been visited yet.
- Push the starting room
Termination:
- Stop the algorithm when
(n-1, m-1)is reached, and return the minimum time recorded.
- Stop the algorithm when
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n * m log(n * m)). - The grid containsn * mcells, and processing each cell involves prioritised exploration using a heap which takes logarithmic time. - 🧺 Space complexity:
O(n * m). - Space required for visited array and grid processing.