Determine if a Cell Is Reachable at a Given Time - Greedy O(1) [JS]
Solution: Greedy
The minimum time from (sx, sy)
to (fx, fy)
is max(diff x, diff y)
.
If the minimum time is less than or equal to t
, it's always possible to reach it in exactly t
moves because we can spend excess moves hopping around the target cell.
The only case where this isn't true is when the two cells start off at the same position and t
is 1
.
We have no choice but to leave the cell and don't have any time to come back.
Time Complexity: O(1)
Space Complexity: O(1)
var isReachableAtTime = function(sx, sy, fx, fy, t) {
if (sx === fx && sy === fy && t === 1) return false;
let diffX = Math.abs(sx - fx), diffY = Math.abs(sy - fy);
return Math.max(diffX, diffY) <= t;
};
Comments
Post a Comment