Skip to content

Commit 7eb5e92

Browse files
refactor 64
1 parent 2797bab commit 7eb5e92

File tree

1 file changed

+32
-30
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+32
-30
lines changed
Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,39 @@
11
package com.fishercoder.solutions;
22

3-
/**64. Minimum Path Sum
4-
5-
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.
6-
7-
Note: You can only move either down or right at any point in time.*/
3+
/**
4+
* 64. Minimum Path Sum
5+
*
6+
* 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.
7+
*
8+
* Note: You can only move either down or right at any point in time.
9+
*/
810
public class _64 {
9-
public static class Solution1 {
10-
/**
11-
* Same idea as _70: have to initialize the first row and the first column and start the for
12-
* loop from i==1 and j==1 for the rest of the matrix.
13-
*/
14-
public int minPathSum(int[][] grid) {
15-
if (grid == null || grid.length == 0) {
16-
return 0;
17-
}
11+
public static class Solution1 {
12+
/**
13+
* Same idea as _70: have to initialize the first row and the first column and start the for
14+
* loop from i==1 and j==1 for the rest of the matrix.
15+
*/
16+
public int minPathSum(int[][] grid) {
17+
if (grid == null || grid.length == 0) {
18+
return 0;
19+
}
1820

19-
int height = grid.length;
20-
int width = grid[0].length;
21-
int[][] dp = new int[height][width];
22-
dp[0][0] = grid[0][0];
23-
for (int i = 1; i < height; i++) {
24-
dp[i][0] = dp[i - 1][0] + grid[i][0];
25-
}
26-
for (int j = 1; j < width; j++) {
27-
dp[0][j] = dp[0][j - 1] + grid[0][j];
28-
}
29-
for (int i = 1; i < height; i++) {
30-
for (int j = 1; j < width; j++) {
31-
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
21+
int height = grid.length;
22+
int width = grid[0].length;
23+
int[][] dp = new int[height][width];
24+
dp[0][0] = grid[0][0];
25+
for (int i = 1; i < height; i++) {
26+
dp[i][0] = dp[i - 1][0] + grid[i][0];
27+
}
28+
for (int j = 1; j < width; j++) {
29+
dp[0][j] = dp[0][j - 1] + grid[0][j];
30+
}
31+
for (int i = 1; i < height; i++) {
32+
for (int j = 1; j < width; j++) {
33+
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
34+
}
35+
}
36+
return dp[height - 1][width - 1];
3237
}
33-
}
34-
return dp[height - 1][width - 1];
3538
}
36-
}
3739
}

0 commit comments

Comments
 (0)