-
Notifications
You must be signed in to change notification settings - Fork 19
/
8.2-Robot_in_a_Grid.py
74 lines (59 loc) · 2.24 KB
/
8.2-Robot_in_a_Grid.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# CTCI 8.2
# Robot in a Grid
#-------------------------------------------------------------------------------
# My Solution
#-------------------------------------------------------------------------------
# BRUTE FORCE O(2^x+y)
#-------------------------------------------------------------------------------
def get_path_brute(grid):
if grid is None or len(grid) == 0:
return None
path = []
if helper(grid, len(grid)-1, len(grid[0])-1, path):
return path
return None
def helper_brute(grid, row, col, path):
if row < 0 or col < 0 or grid[row][col] is None:
return False
# If at origin then the path has made it all the way!
if (row == 0 and col == 0) or helper_brute(grid, row-1, col, path) or helper_brute(grid, row, col-1, path):
path.append((row,col))
return True
return False
#-------------------------------------------------------------------------------
# DYNAMIC PROGRAMMING O(XY)
#-------------------------------------------------------------------------------
def get_path(grid):
if grid is None or len(grid) == 0:
return None
path = []
failed = []
if helper(grid, len(grid)-1, len(grid[0])-1, path, failed):
return path
return None
def helper(grid, row, col, path, failed):
if row < 0 or col < 0 or grid[row][col] is None:
return False
point = (row,col)
# Already visited this and failed!
if point in failed:
return False
# If at origin then the path has made it all the way!
if point == (0,0) or helper(grid, row-1, col, path, failed) or helper(grid, row, col-1, path, failed):
path.append(point)
return True
failed.append(point)
return False
#-------------------------------------------------------------------------------
#Testing
#-------------------------------------------------------------------------------
import unittest
class Test(unittest.TestCase):
def test_path_through_grid(self):
grid = [[0, 0, 0, 0, 0, 0, None],
[0, None, None, 0, None, None, 0],
[0, 0, None, 0, 0, 0, 0],
[None, None, 0, 0, 0, None, 0]]
print(get_path(grid))
if __name__ == "__main__":
unittest.main()