Problem Description
You are given an n x m grid where each cell (i, j) has a moveTime value that represents the earliest time you are allowed to start moving into that room. Starting at room (0, 0) at time t = 0, you must reach room (n - 1, m - 1) by moving to an adjacent room (sharing a common wall). The twist is that the time cost for moves alternates: the first move takes 1 second, the second move takes 2 seconds, then 1 second, and so on. Determine the minimum time required to reach the destination while respecting the moveTime constraints.
Key Insights
- The problem can be modeled as a graph traversal where each state is defined by the room coordinates (r, c) and the parity (even or odd move count) indicating whether the next move costs 1 second (even) or 2 seconds (odd).
- Dijkstra's algorithm is well-suited because the waiting time (if the move is attempted before the allowed moveTime) and the alternating move durations create weighted edges.
- Each state transition (to an adjacent room) computes the next available time by taking the maximum between the current time and the allowed move time, then adding the required move duration.
- The grid has up to about 750x750 cells, and each cell has two states (depending on parity), so efficiency in both time and space is crucial.
Space and Time Complexity
Time Complexity: O(nmlog(nm)) – each state (cell with parity) is processed using a priority queue. Space Complexity: O(nm) – to store the minimum time required to reach each state.
Solution
We use Dijkstra's algorithm to traverse the grid where the state is represented by (row, column, parity). The parity indicates whether the next move takes 1 second (when parity == 0) or 2 seconds (when parity == 1). For each move:
- Check each adjacent cell.
- Wait until the moveTime for that cell if necessary.
- Add 1 or 2 seconds based on the current parity.
- Switch the parity for the next move. We maintain a priority queue (min-heap) to always process the state with the smallest current time, ensuring the optimal solution is found. Edge updating is done when a better (smaller time) state is found.