Leetcode # 2849. Determine if a Cell Is Reachable at a Given Time
- 2023.09.10
- Uncategorized
Problem
Testcases
# | Input | Expected |
1
|
1
1
1
1
3
|
True |
2
|
1
2
1
2
1
|
False |
3
|
1
3
1
3
0
|
True |
4
|
1
1
2
1
2
|
True |
Solution
- 可以斜走 ⇒ x, y 方向可以同時用 1 秒拉近 1 單位距離
⇒ 從 (sx, sy) 到 (fx, fy) 的最小步數為 max(abs(fx – sx), abs(fy – sy)) - 餘下的秒數 (t – 最小步數) > 0
- 來回走消耗 2k 秒
- 消耗掉 2k 時間後,還剩餘 1 秒:
- 有斜走 ⇒ 拆成縱和橫,消耗掉剩餘的 1 秒
- 無斜走 ⇒ 將[縱/橫]改為斜走,在消耗掉消耗掉剩餘的 1 秒將另外一個維度調整回來
ex: [+1, 0] -> [+1, +1] + [0, -1] - 2-2-1 和 2-2-2 需要 t >= 2
⇔ 起點和終點相同,但t
為1
時,return
為False
Time Complexity: O(1)
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)
class Solution: def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool: min_seconds = max(abs(fx - sx), abs(fy - sy)) return t == min_seconds or (t > min_seconds and t >= 2)
Last Updated on 2023/09/10 by A1go