Skip to content

Commit 4ae9de8

Browse files
committed
num paths in n m matrix.
1 parent cf607df commit 4ae9de8

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Problem Statement
3+
=================
4+
5+
Count the number of Paths from 1,1 to N,M in an NxM matrix.
6+
7+
Analysis
8+
--------
9+
10+
* Dynamic Programing Solution: O(rows * cols)
11+
* Recursive: O(2^rows) if rows > cols else O(2^cols)
12+
13+
14+
References
15+
----------
16+
* http://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
17+
18+
"""
19+
20+
21+
def num_paths_matrix(rows, cols):
22+
T = [[1 if row == 0 or col == 0 else 0 for row in range(cols)] for col in range(rows)]
23+
for row in range(1, rows):
24+
for col in range(1, cols):
25+
T[row][col] = T[row - 1][col] + T[row][col - 1]
26+
return T[rows - 1][cols - 1]
27+
28+
29+
def num_paths_matrix_recursive(rows, cols):
30+
if rows == 1 or cols == 1:
31+
return 1
32+
return num_paths_matrix(rows-1, cols) + num_paths_matrix(rows, cols - 1)
33+
34+
35+
if __name__ == '__main__':
36+
rows = 3
37+
cols = 3
38+
expected = 6
39+
assert expected == num_paths_matrix(rows, cols)
40+
assert expected == num_paths_matrix_recursive(rows, cols)

0 commit comments

Comments
 (0)