File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed
kotlin/Dynamic Programming Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ fun matrixPathways (m : Int , n : Int ): Int {
2
+ // Base cases: Set all cells in row 0 and column 0 to 1. We can
3
+ // do this by initializing all cells in the DP table to 1.
4
+ val dp = Array (m) { IntArray (n) { 1 } }
5
+ // Fill in the rest of the DP table.
6
+ for (r in 1 until m) {
7
+ for (c in 1 until n) {
8
+ // Paths to current cell = paths from above + paths from
9
+ // left.
10
+ dp[r][c] = dp[r - 1 ][c] + dp[r][c - 1 ]
11
+ }
12
+ }
13
+ return dp[m - 1 ][n - 1 ]
14
+ }
Original file line number Diff line number Diff line change
1
+ fun matrixPathwaysOptimized (m : Int , n : Int ): Int {
2
+ // Initialize 'prevRow' as the DP values of row 0, which are all 1s.
3
+ var prevRow = IntArray (n) { 1 }
4
+ // Iterate through the matrix starting from row 1.
5
+ for (r in 1 until m) {
6
+ // Set the first cell of 'currRow' to 1. This is done by
7
+ // setting the entire row to 1.
8
+ val currRow = IntArray (n) { 1 }
9
+ for (c in 1 until n) {
10
+ // The number of unique paths to the current cell is the sum
11
+ // of the paths from the cell above it ('prevRow[c]') and
12
+ // the cell to the left ('currRow[c - 1]').
13
+ currRow[c] = prevRow[c] + currRow[c - 1 ]
14
+ }
15
+ // Update 'prevRow' with 'currRow' values for the next
16
+ // iteration.
17
+ prevRow = currRow
18
+ }
19
+ // The last element in 'prevRow' stores the result for the
20
+ // bottom-right cell.
21
+ return prevRow[n - 1 ]
22
+ }
You can’t perform that action at this time.
0 commit comments