File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int minPathSum (vector<vector<int >>& grid) {
4
+ int m = grid.size (); // number of rows
5
+ int n = grid[0 ].size (); // number of columns
6
+
7
+ for (int i = 0 ; i < m; ++i){
8
+ for (int j = 0 ; j < n; ++j) {
9
+ if (i == 0 && j==0 ) continue ;
10
+ if (i==0 ) { // for first row cells
11
+ grid[i][j] += grid[i][j-1 ]; // add from the cell left to it
12
+ continue ; // go back to the loop
13
+ }
14
+ if (j ==0 ) { // for the first column cells
15
+ grid[i][j] += grid[i-1 ][j]; // add from the cells above it
16
+ continue ;
17
+ }
18
+ // for any other cell
19
+ // sum by adding from the cell above it
20
+ int topSum = grid[i][j] + grid[i-1 ][j];
21
+ // sum by adding from the cell left to it
22
+ int leftSum = grid[i][j] + grid[i][j-1 ];
23
+ // choose the minimum sum path
24
+ grid[i][j] = min (topSum, leftSum);
25
+ }
26
+ }
27
+
28
+ return grid[m-1 ][n-1 ];
29
+ }
30
+ };
You can’t perform that action at this time.
0 commit comments