File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int minFallingPathSum(vector<vector<int>>& matrix) {
4
+ int n = matrix.size(); // Get the size of the matrix
5
+ int first_min = 1e9, second_min = 1e9; // Initialize first and second minimums to a large value
6
+ int first_index = -1, second_index = -1; // Initialize indices for the first and second minimums
7
+
8
+ // Iterate through each row of the matrix
9
+ for(int i = 0; i < n; i++) {
10
+ if(i != 0) { // For rows after the first one
11
+ // Update the matrix values based on previous row's minimums
12
+ for(int j = 0; j < n; j++) {
13
+ if(j != first_index)
14
+ matrix[i][j] += first_min;
15
+ else
16
+ matrix[i][j] += second_min;
17
+ }
18
+ }
19
+
20
+ // Reset first and second minimums for the current row
21
+ first_min = 1e9;
22
+ second_min = 1e9;
23
+
24
+ // Iterate through each element of the current row
25
+ for(int j = 0; j < n; j++) {
26
+ // Update first and second minimums and their indices
27
+ if(matrix[i][j] < first_min) {
28
+ second_min = first_min;
29
+ first_min = matrix[i][j];
30
+ first_index = j;
31
+ } else if(matrix[i][j] < second_min) {
32
+ second_min = matrix[i][j];
33
+ second_index = j;
34
+ }
35
+ }
36
+ }
37
+
38
+ // Return the minimum of the first and second minimums
39
+ return min(first_min, second_min);
40
+ }
41
+ };
You can’t perform that action at this time.
0 commit comments