Skip to content

Commit

Permalink
Add solution for Check if There is a Valid Path in a Grid
Browse files Browse the repository at this point in the history
  • Loading branch information
Blacknahil committed Apr 3, 2024
1 parent 4ab7a5a commit 34af2e0
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions camp1/week3/leetcode/check-if-there-is-a-valid-path-in-a-grid.py
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)


0 comments on commit 34af2e0

Please sign in to comment.