Skip to content

Commit a7a268c

Browse files
committed
Added code to find the number of unique paths
starting from the top left cell to the bottom right cell of the matrix.
1 parent 76c50d6 commit a7a268c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

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)