forked from mission-peace/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnum_paths_nm_matrix.py
More file actions
40 lines (28 loc) · 978 Bytes
/
num_paths_nm_matrix.py
File metadata and controls
40 lines (28 loc) · 978 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
33
34
35
36
37
38
39
40
"""
Problem Statement
=================
Count the number of Paths from 1,1 to N,M in an NxM matrix.
Analysis
--------
* Dynamic Programing Solution: O(rows * cols)
* Recursive: O(2^rows) if rows > cols else O(2^cols)
References
----------
* http://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
"""
def num_paths_matrix(rows, cols):
T = [[1 if row == 0 or col == 0 else 0 for row in range(cols)] for col in range(rows)]
for row in range(1, rows):
for col in range(1, cols):
T[row][col] = T[row - 1][col] + T[row][col - 1]
return T[rows - 1][cols - 1]
def num_paths_matrix_recursive(rows, cols):
if rows == 1 or cols == 1:
return 1
return num_paths_matrix(rows-1, cols) + num_paths_matrix(rows, cols - 1)
if __name__ == '__main__':
rows = 3
cols = 3
expected = 6
assert expected == num_paths_matrix(rows, cols)
assert expected == num_paths_matrix_recursive(rows, cols)