forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck-if-there-is-a-valid-path-in-a-grid.py
More file actions
33 lines (31 loc) · 1.07 KB
/
check-if-there-is-a-valid-path-in-a-grid.py
File metadata and controls
33 lines (31 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def hasValidPath(self, grid):
"""
:type grid: List[List[int]]
:rtype: bool
"""
E, S, W, N = [(0, 1), (1, 0), (0, -1), (-1, 0)]
directions = [
[W, E], [N, S],
[W, S], [S, E],
[W, N], [N, E]
]
for r, c in directions[grid[0][0]-1]:
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])):
continue
pr, pc = 0, 0
while r != len(grid)-1 or c != len(grid[0])-1:
for dx, dy in directions[grid[r][c]-1]:
nr, nc = r+dx, c+dy
if (nr == pr and nc == pc) or \
not(0 <= nr < len(grid) and 0 <= nc < len(grid[0])) or \
(-dx, -dy) not in directions[grid[nr][nc]-1]:
continue
pr, pc, r, c = r, c, nr, nc
break
else:
return False
return True
return len(grid) == len(grid[0]) == 1