Skip to content

Commit e97917f

Browse files
authored
64. Minimum Path Sum - DP with no Extra space
64. Minimum Path Sum - DP with no Extra space
1 parent cc26911 commit e97917f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Dynamic-Programming/minPathSum.cpp

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

0 commit comments

Comments
 (0)