#2849

Determine if a Cell Is Reachable at a Given Time

Medium
MathMathGrid Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution leverages the properties of the Chebyshev distance to determine if the target cell can be reached in exactly 't' seconds. This approach is efficient and avoids unnecessary calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the Chebyshev distance between (sx, sy) and (fx, fy).
  2. 2Step 2: Check if the distance is less than or equal to 't'.
  3. 3Step 3: If the distance is less than 't', ensure that the remaining time (t - distance) is even to allow for backtracking.
solution.py9 lines
1# Full working Python code
2
3def isReachable(sx, sy, fx, fy, t):
4    distance = max(abs(fx - sx), abs(fy - sy))
5    return distance <= t and (t - distance) % 2 == 0
6
7# Example usage
8print(isReachable(2, 4, 7, 7, 6))  # Output: True
9print(isReachable(3, 1, 7, 3, 3))  # Output: False

Complexity note: The optimal solution has constant time and space complexity due to the simple arithmetic operations involved.

  • 1The Chebyshev distance is crucial for determining the minimum time required to reach the target cell.
  • 2The parity of the remaining time after reaching the target distance is important for ensuring we can use the time effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.