File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff 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 )
Original file line number Diff line number Diff line change 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 ()
You can’t perform that action at this time.
0 commit comments