Skip to content

Commit 65727ca

Browse files
committed
Refine the solution for #64
1 parent 663b05b commit 65727ca

File tree

1 file changed

+17
-21
lines changed

1 file changed

+17
-21
lines changed

src/main/java/org/sean/recursive/MinPathFinder.java

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,9 @@ public class MinPathFinder {
99
private int column;
1010

1111
public int minPathSum(int[][] grid) {
12-
if (grid == null || grid.length == 0)
13-
return 0;
12+
if (grid == null || grid.length == 0) return 0;
1413

15-
if (grid.length == 1 && grid[0].length == 1)
16-
return grid[0][0];
14+
if (grid.length == 1 && grid[0].length == 1) return grid[0][0];
1715

1816
// m
1917
row = grid.length;
@@ -22,38 +20,36 @@ public int minPathSum(int[][] grid) {
2220

2321
marks = new int[row][column];
2422

25-
int minSum = calcMinSum(grid, row - 1, column - 1);
26-
return minSum;
23+
return calcMinSum(grid, row - 1, column - 1);
2724
}
2825

2926
private int calcMinSum(int[][] grid, int row, int column) {
3027
if (row < 0 || column < 0) {
31-
return 0;
28+
return -1; // non-negative values for each cell
3229
}
3330

3431
if (marks[row][column] != 0) {
3532
return marks[row][column];
3633
}
3734

38-
int sumMin = grid[row][column];
39-
if (row == 0 || column == 0) {
40-
if (row == 0 && column == 0) {
41-
return grid[0][0];
42-
}
43-
44-
if (row == 0) {
45-
return sumMin + calcMinSum(grid, row, column - 1);
46-
} else {
47-
// column == 0
48-
return sumMin + calcMinSum(grid, row - 1, column);
49-
}
50-
35+
if (row == 0 && column == 0) {
36+
return grid[0][0];
5137
}
5238

39+
int sumMin = grid[row][column];
40+
5341
int topResult = calcMinSum(grid, row - 1, column);
5442
int leftResult = calcMinSum(grid, row, column - 1);
5543

56-
int sum = sumMin + Math.min(leftResult, topResult);
44+
int subMin;
45+
if (topResult >= 0 && leftResult >= 0) {
46+
// Calling method Math.min() takes extra time!
47+
subMin = leftResult < topResult ? leftResult : topResult;
48+
} else {
49+
subMin = topResult < 0 ? leftResult : topResult;
50+
}
51+
52+
int sum = sumMin + subMin;
5753

5854
marks[row][column] = sum;
5955
return sum;

0 commit comments

Comments
 (0)