forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsol2.py
More file actions
32 lines (23 loc) · 733 Bytes
/
sol2.py
File metadata and controls
32 lines (23 loc) · 733 Bytes
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
"""
Problem 15: https://projecteuler.net/problem=15
Starting in the top left corner of a 2x2 grid, and only being able to move to
the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20x20 grid?
"""
def solution(n: int = 20) -> int:
"""
Solve by explicitly counting the paths with dynamic programming.
>>> solution(6)
924
>>> solution(2)
6
>>> solution(1)
2
"""
counts = [[1 for _ in range(n + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
counts[i][j] = counts[i - 1][j] + counts[i][j - 1]
return counts[n][n]
if __name__ == "__main__":
print(solution())