#1391
Check if There is a Valid Path in a Grid
MediumArrayDepth-First SearchBreadth-First SearchUnion-FindMatrixGraph TraversalBreadth-First SearchDepth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n) | O(m * n) |
| Space | O(m * n) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
We can optimize the brute-force approach by using a queue for Breadth-First Search (BFS) to explore the grid iteratively. This allows us to explore all possible paths more efficiently and avoid deep recursion.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a queue and add the starting cell (0, 0).
- 2Step 2: While the queue is not empty, pop the front cell.
- 3Step 3: Check if the current cell is the destination cell (m-1, n-1).
- 4Step 4: For the current cell, determine possible moves based on the street type.
- 5Step 5: If a move is valid and the next cell has not been visited, add it to the queue.
solution.py20 lines
1from collections import deque
2
3def hasValidPath(grid):
4 m, n = len(grid), len(grid[0])
5 visited = set()
6 queue = deque([(0, 0)])
7 directions = {1: [(0, 1), (0, -1)], 2: [(1, 0), (-1, 0)], 3: [(0, -1), (1, 0)], 4: [(0, 1), (1, 0)], 5: [(0, -1), (-1, 0)], 6: [(0, 1), (-1, 0)]}
8
9 while queue:
10 x, y = queue.popleft()
11 if (x, y) in visited:
12 continue
13 if (x, y) == (m-1, n-1):
14 return True
15 visited.add((x, y))
16 for dx, dy in directions[grid[x][y]]:
17 nx, ny = x + dx, y + dy
18 if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited:
19 queue.append((nx, ny))
20 return Falseℹ
Complexity note: The time complexity remains O(m * n) as we may still visit every cell. The space complexity is O(m * n) due to the visited array and the queue used for BFS.
- 1Understanding the street types and their connections is crucial.
- 2Using BFS can help avoid deep recursion and stack overflow issues.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.