Skip to content

Commit c3e5b14

Browse files
committed
add solution of problem 64: minimun path sum
1 parent 2330e68 commit c3e5b14

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

MinimunPathSum64/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Given a *m* x *n* grid filled with non-negative numbers, find a path from top left to bottom right which *minimizes* the sum of all numbers along its path.
2+
3+
**Note:** You can only move either down or right at any point in time.

MinimunPathSum64/Solution.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
public class Solution {
2+
public int minPathSum(int[][] grid) {
3+
if (grid == null || grid.length == 0 || grid[0].length == 0)
4+
return 0;
5+
6+
int rowLen = grid.length;
7+
int colLen = grid[0].length;
8+
int[][] pathSum = new int[rowLen][colLen];
9+
int lastRowIdx = rowLen - 1;
10+
int lastColIdx = colLen - 1;
11+
int lastButOneRowIdx = lastRowIdx - 1;
12+
int lastButOneColIdx = lastColIdx - 1;
13+
14+
pathSum[lastRowIdx][lastColIdx] = grid[lastRowIdx][lastColIdx];
15+
16+
for (int row = lastRowIdx, col = lastButOneColIdx; col >= 0; col--) {
17+
pathSum[row][col] += pathSum[row][col+1] + grid[row][col];
18+
}
19+
20+
for (int row = lastButOneRowIdx, col = lastColIdx; row >= 0; row--) {
21+
pathSum[row][col] += pathSum[row+1][col] + grid[row][col];
22+
}
23+
24+
for (int row = lastButOneRowIdx; row >= 0; row--) {
25+
for (int col = lastButOneColIdx; col >= 0; col--) {
26+
int rowBelow = row + 1;
27+
int colRight = col + 1;
28+
int minValue = pathSum[rowBelow][col] < pathSum[row][colRight] ? pathSum[rowBelow][col] : pathSum[row][colRight];
29+
pathSum[row][col] += grid[row][col] + minValue;
30+
}
31+
}
32+
33+
return pathSum[0][0];
34+
}
35+
}

0 commit comments

Comments
 (0)