Skip to content

Commit 2efa03a

Browse files
committed
Add Matrix Pathways
1 parent 3013089 commit 2efa03a

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}

0 commit comments

Comments
 (0)