Sliding Marble on a Tiltable Grid with Scheduled Tilts
Arrays & HashingAuto-graded · 21 test casesLast updated
Simulate a marble on a grid whose tilt changes at scheduled times, and find its final cell efficiently when the end time can reach a billion seconds.
A rectangular grid contains a single marble and sits on a platform that can be tilted. The platform is always in exactly one of five modes: "up", "down", "left", "right" or "flat".
Whenever the platform is tilted (any mode other than "flat"), the marble tries to move one cell per second in the tilt direction. It moves only if the neighboring cell in that direction is inside the grid and open.
You are given the grid, the marble's starting cell, a list of scheduled tilt changes, and a finishing time. Return the cell where the marble is at the finishing time.
Function
Implement slide_marble(grid, start, changes, end_time).
gridis a list of strings.grid[i][j]is'#'for a wall and'.'for an open cell.startis[row, col], the starting cell.changesis a list of(time, mode)pairs. Each pair sets the platform tomodestarting at secondtime.end_timeis the finishing time.- Return
[row, col], the marble's cell at timeend_time.
Rules
- Row
0is the top row and column0is the leftmost column. From(row, col),"up"leads to(row - 1, col),"down"to(row + 1, col),"left"to(row, col - 1)and"right"to(row, col + 1). - Time is counted in whole seconds. Before the first change, the platform is
"flat". A change(t, mode)takes effect at the start of secondtand lasts until the next change. - For each second
s = 0, 1, ..., end_time - 1, the mode during that second is the mode of the last change withtime <= s, or"flat"if there is no such change. - If that mode is not
"flat"and the neighbor in that direction is inside the grid and open, the marble moves into it at the end of that second. Otherwise it stays where it is. - Cells outside the grid count as walls, so the marble can never leave the grid.
- Changes with
time >= end_timehave no effect. - If
end_timeis0, the answer isstart.
Constraints
1 <= len(grid) <= 100and1 <= len(grid[0]) <= 100. All rows have equal length and contain only'#'and'.'.startis an open cell.0 <= len(changes) <= 10^40 <= time <= 10^9for every change, and change times are strictly increasing.- Every
modeis one of"up","down","left","right","flat". 0 <= end_time <= 10^9
Examples
Example 1
Input: slide_marble(['#######', '#.....#', '#.###.#', '#.....#', '#######'], [1, 1], [[0, 'right'], [2, 'flat'], [5, 'down'], [8, 'right']], 12)
Output: [1, 5]
Example 2
Input: slide_marble(['#######', '#.....#', '#.###.#', '#.....#', '#######'], [1, 5], [[1, 'down'], [3, 'left'], [100, 'up']], 103)
Output: [1, 1]
Example 3
Input: slide_marble(['..', '..'], [0, 0], [[0, 'left'], [1, 'down'], [2, 'right'], [4, 'up']], 4)
Output: [1, 1]
Hints
Hint 1
Simulating every single second is too slow when end_time can be 10^9. Notice that the tilt mode only changes at the scheduled times.
Hint 2
Split the timeline into segments between consecutive changes (the last segment ends at end_time, and changes at or after end_time are dropped). Inside one segment the direction is fixed.
Hint 3
Within a segment, once the marble is blocked by a wall or the edge it stays blocked for the rest of that segment, so stop early. Each segment then costs at most about max(rows, cols) moves.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulating each of up to 10^9 seconds is far too slow. The mode only changes at scheduled times, so the timeline splits into at most len(changes) + 1 segments in which the tilt is constant.
- Discard every change with
time >= end_time, since it cannot affect any second in[0, end_time). - Walk the remaining changes in order. Change
igoverns the seconds from its own time up to the next kept change's time, or up toend_timefor the last one. The period before the first change is flat, so the marble does not move. - For a
"flat"segment, do nothing. - For a tilted segment, repeatedly check the neighbor in the tilt direction. If it is inside the grid and open, move there and use up one second. If it is blocked, stop immediately and skip the rest of the segment.
Why it is correct
- For any second
s, the governing mode is the one set by the last change withtime <= s. Ift_i <= s < t_{i+1}, that is changei, so the segments match the rules exactly. Strictly increasing times mean the segments do not overlap. - Early termination is safe. If the neighbor is blocked in some second, the marble stays put. In the next second of the same segment the direction and the grid are unchanged, so the same neighbor is checked and is still blocked. By induction the marble stays still for the rest of the segment.
- Out-of-grid cells are treated as walls by the bounds check, which runs before the grid is indexed.
- Edge cases follow naturally:
end_time = 0filters out every change and returnsstart, and a change at exactlyend_timeis filtered out.
Complexity
- Time:
O(E * max(H, W)), whereEis the number of changes. In one segment the marble moves in a straight line, so it makes at mostmax(H, W) - 1successful moves plus one failed check. The cost does not depend onend_time. - Space:
O(E)for the filtered list of changes.
Reference solution
from typing import List, Tuple
def slide_marble(grid: List[str], start: List[int], changes: List[Tuple[int, str]], end_time: int) -> List[int]:
h = len(grid)
w = len(grid[0])
deltas = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}
r, c = start[0], start[1]
# Only changes strictly before end_time can influence any second in [0, end_time).
active = [(t, m) for t, m in changes if t < end_time]
for i, (t, mode) in enumerate(active):
seg_end = active[i + 1][0] if i + 1 < len(active) else end_time
remaining = seg_end - t
if mode == "flat" or remaining <= 0:
continue
dr, dc = deltas[mode]
while remaining > 0:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w and grid[nr][nc] == ".":
r, c = nr, nc
remaining -= 1
else:
break
return [r, c]