-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid_traveller.py
More file actions
66 lines (50 loc) · 1.66 KB
/
grid_traveller.py
File metadata and controls
66 lines (50 loc) · 1.66 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
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
"""
Python implementation of the second and the tenth chapters code.
Original videos can be viewed from the following link:
https://www.youtube.com/watch?v=oBt53YbR9Kk
"""
# Second Chapter
def grid_traveller(m: int, n: int):
"""
Returns the number of ways as int within the given grid size.
Assumes that initial location is 0, 0 (top left).
"""
if m == 1 and n == 1:
return 1
if m == 0 or n == 0:
return 0
return grid_traveller(m - 1, n) + grid_traveller(m, n - 1)
def mem_grid_traveller(m: int, n: int, memo: dict={}):
"""
Returns the number of ways as int within the given grid size.
Assumes that initial location is 0, 0 (top left).
"""
value = memo.get((m, n))
if not value:
if m == 1 and n == 1:
value = 1
elif m == 0 or n == 0:
value = 0
else:
value = mem_grid_traveller(m - 1, n, memo) + mem_grid_traveller(m, n - 1, memo)
memo[(m, n)] = value
return value
# Tenth Chapter
def tab_grid_traveller(m: int, n: int):
"""
Returns the number of ways as int within the given grid size.
Assumes that initial location is 0, 0 (top left).
"""
if m == 1 and n == 1:
return 1
if m == 0 or n == 0:
return 0
table = [[0 for j in range(n + 1)] for i in range(m + 1)] # Initialize table with m + 1 rows and n + 1 columns.
table[1][1] = 1
for i in range(m + 1):
for j in range(n + 1):
if j + 1 <= n:
table[i][1 + j] = table[i][1 + j] + table[i][j]
if i + 1 <= m:
table[i + 1][j] = table[i + 1][j] + table[i][j]
return table[m][n]