#3286
Find a Safe Walk Through a Grid
MediumArrayBreadth-First SearchGraph TheoryHeap (Priority Queue)MatrixShortest PathGraph TraversalBreadth-First SearchDepth-First Search
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)
The optimal solution uses a Breadth-First Search (BFS) approach with a queue to explore the grid. This allows us to find the shortest path while efficiently managing health points, ensuring we only explore viable paths.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a queue with the starting position (0, 0) and the initial health.
- 2Step 2: While the queue is not empty, dequeue an element and check if it's the bottom-right corner.
- 3Step 3: For each valid move (up, down, left, right), calculate the new health and enqueue the new position if health is still positive and not visited.
- 4Step 4: Continue until the queue is empty or the destination is reached.
solution.py24 lines
1# Full working Python code
2from collections import deque
3from typing import List
4
5def canReach(grid: List[List[int]], health: int) -> bool:
6 m, n = len(grid), len(grid[0])
7 queue = deque([(0, 0, health)])
8 visited = set()
9 directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
10
11 while queue:
12 x, y, h = queue.popleft()
13 if (x, y) == (m - 1, n - 1) and h >= 1:
14 return True
15 visited.add((x, y))
16
17 for dx, dy in directions:
18 nx, ny = x + dx, y + dy
19 if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited:
20 next_health = h - grid[nx][ny]
21 if next_health > 0:
22 queue.append((nx, ny, next_health))
23
24 return Falseℹ
Complexity note: The time complexity is O(n) as we explore each cell at most once. The space complexity is O(n) due to the queue used for BFS.
- 1Using BFS ensures we explore the shortest paths first, which is crucial for pathfinding problems.
- 2Tracking visited nodes prevents cycles and unnecessary re-exploration.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.