#3235
Check if the Rectangle Corner Is Reachable
HardArrayMathDepth-First SearchBreadth-First SearchUnion-FindGeometryGraph Traversal (BFS/DFS)Geometry
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking every point, we can model the problem as a graph where edges represent possible movements. We can use a BFS or DFS to explore paths while avoiding circles.
⚙️
Algorithm
3 steps- 1Step 1: Create a graph with vertices representing the edges of the rectangle and circles.
- 2Step 2: For each edge, check if it can connect to another edge without intersecting any circles.
- 3Step 3: Use BFS or DFS to find a path from the bottom left corner to the top right corner.
solution.py21 lines
1from collections import deque
2
3def is_path_reachable(xCorner, yCorner, circles):
4 def can_connect(x1, y1, x2, y2):
5 for cx, cy, r in circles:
6 if (x1 - cx) ** 2 + (y1 - cy) ** 2 < r ** 2 and (x2 - cx) ** 2 + (y2 - cy) ** 2 < r ** 2:
7 return False
8 return True
9
10 queue = deque([(0, 0)])
11 visited = set((0, 0))
12 while queue:
13 x, y = queue.popleft()
14 if x == xCorner and y == yCorner:
15 return True
16 for dx, dy in [(1, 0), (0, 1)]:
17 nx, ny = x + dx, y + dy
18 if 0 <= nx <= xCorner and 0 <= ny <= yCorner and (nx, ny) not in visited and can_connect(x, y, nx, ny):
19 visited.add((nx, ny))
20 queue.append((nx, ny))
21 return Falseℹ
Complexity note: The time complexity is O(n) because we only explore each edge once, and the space complexity is O(n) due to the storage of visited nodes.
- 1The path must avoid all circles while staying within the rectangle.
- 2Modeling the problem as a graph allows efficient exploration of possible paths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.