Skip to content

Commit da031f6

Browse files
authored
Merge pull request keon#60 from ankit167/count_paths_in_a_matrix
Added code to find the number of unique paths in a matrix
2 parents 24ec9a9 + b07e808 commit da031f6

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ Minimal and clean example implementations of data structures and algorithms in P
112112
- [sparse_dot_vector](matrix/sparse_dot_vector.py)
113113
- [sparse_mul](matrix/sparse_mul.py)
114114
- [spiral_traversal](matrix/spiral_traversal.py)
115+
- [count_paths](matrix/count_paths.py)
115116
- [queue](queue)
116117
- [max_sliding_window](queue/max_sliding_window.py)
117118
- [moving_average](queue/moving_average.py)

matrix/count_paths.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
3+
#
4+
# Count the number of unique paths from a[0][0] to a[m-1][n-1]
5+
# We are allowed to move either right or down from a cell in the matrix.
6+
# Approaches-
7+
# (i) Recursion- Recurse starting from a[m-1][n-1], upwards and leftwards,
8+
# add the path count of both recursions and return count.
9+
# (ii) Dynamic Programming- Start from a[0][0].Store the count in a count
10+
# matrix. Return count[m-1][n-1]
11+
# T(n)- O(mn), S(n)- O(mn)
12+
#
13+
def count_paths(m, n):
14+
if m < 1 or n < 1:
15+
return -1
16+
count = [[None for j in range(n)] for i in range(m)]
17+
18+
# Taking care of the edge cases- matrix of size 1xn or mx1
19+
for i in range(n):
20+
count[0][i] = 1
21+
for j in range(m):
22+
count[j][0] = 1
23+
24+
for i in range(1, m):
25+
for j in range(1, n):
26+
# Number of ways to reach a[i][j] = number of ways to reach
27+
# a[i-1][j] + a[i][j-1]
28+
count[i][j] = count[i-1][j] + count[i][j-1]
29+
30+
print count[m-1][n-1]
31+
32+
33+
def main():
34+
m, n = map(int, raw_input().split())
35+
count_paths(m, n)
36+
37+
if __name__ == '__main__':
38+
main()

0 commit comments

Comments
 (0)