Ctrl K

Rooms on a Timer

Hard
A museum is laid out as an m × n grid of rooms opens. The room in row r and column c opens at time opens[r][c]: you may enter it only at a moment no earlier than that. At time 0 you stand in the top-left room. Every second you must move to an adjacent room (up, down, left or right); staying put is not allowed. Each move takes exactly one second. Return the earliest time at which you can be in the bottom-right room, or -1 if it cannot be reached.
Example 1
opens=[[0, 1], [3, 2]] → 2

At time 1 we step right (that room opened at time 1), and at time 2 we step down into the bottom-right room, which opens exactly at time 2.

Example 2
opens=[[0, 4], [5, 6]] → -1

Both neighbours of the starting room are still closed at time 1, and standing still is not allowed, so there is nowhere to go.

Example 3
opens=[[0, 1, 1], [9, 9, 6]] → 7

By time 2 we are in the top-right room, but the room below it opens only at time 6. We pace back and forth between the two top-right rooms; because of parity we can step down only at time 7.

Constraints
  • 2 ≤ m, n ≤ 1000
  • 4 ≤ m · n ≤ 10⁵
  • 0 ≤ opens[r][c] ≤ 10⁵
  • opens[0][0] = 0
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBall Into the Hole HardRepaint Arrows to Reach the Exit HardThrough the Walls to the Far Corner HardShortest Path of a Rolling Ball MediumAcross the Hazard Field Medium
loading Python…
Input
opens=[[0, 1], [3, 2]]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.