Skip to content

Commit 1d5bf98

Browse files
committed
add: MatrixPathwaysOptimized
1 parent 72b875b commit 1d5bf98

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.Arrays;
2+
3+
public class MatrixPathwaysOptimized {
4+
public int matrixPathwaysOptimized(int m, int n) {
5+
// Initialize 'prevRow' as the DP values of row 0, which are all 1s.
6+
int[] prevRow = new int[n];
7+
Arrays.fill(prevRow, 1);
8+
// Iterate through the matrix starting from row 1.
9+
for (int r = 1; r < m; r++) {
10+
// Set the first cell of 'curr_row' to 1. This is done by
11+
// setting the entire row to 1.
12+
int[] currRow = new int[n];
13+
Arrays.fill(currRow, 1);
14+
for (int c = 1; c < n; c++) {
15+
// The number of unique paths to the current cell is the sum
16+
// of the paths from the cell above it ('prevRow[c]') and
17+
// the cell to the left ('currRow[c - 1]').
18+
currRow[c] = prevRow[c] + currRow[c - 1];
19+
}
20+
// Update 'prevRow' with 'currRow' values for the next
21+
// iteration.
22+
prevRow = currRow;
23+
}
24+
// The last element in 'prevRow' stores the result for the
25+
// bottom-right cell.
26+
return prevRow[n - 1];
27+
}
28+
}

0 commit comments

Comments
 (0)