-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add solution for Check if There is a Valid Path in a Grid
- Loading branch information
1 parent
4ab7a5a
commit 34af2e0
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
26 changes: 26 additions & 0 deletions
26
camp1/week3/leetcode/check-if-there-is-a-valid-path-in-a-grid.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
class Solution: | ||
def hasValidPath(self, grid: List[List[int]]) -> bool: | ||
directions={1:[(0,-1),(0,1)],2:[(1,0),(-1,0)], | ||
3:[(0,-1),(1,0)],4:[(0,1),(1,0)],5:[(-1,0),(0,-1)], | ||
6:[(0,1),(-1,0)] | ||
} | ||
visited=set() | ||
def inbound(r,c): | ||
return 0<=r<len(grid) and 0<=c<len(grid[0]) | ||
def dfs(r,c): | ||
if r==len(grid)-1 and c==len(grid[0])-1: | ||
return True | ||
visited.add((r,c)) | ||
for dr,dc in directions[grid[r][c]]: | ||
new_row=dr+r | ||
new_col=dc+c | ||
if not inbound(new_row,new_col): | ||
continue | ||
if (new_row,new_col) not in visited and (-dr,-dc) in directions[grid[new_row][new_col]]: | ||
found=dfs(new_row,new_col) | ||
if found: | ||
return True | ||
return False | ||
return dfs(0,0) | ||
|
||
|