-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinPathSum.java
More file actions
58 lines (51 loc) · 1.44 KB
/
MinPathSum.java
File metadata and controls
58 lines (51 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MinPathSum {
int n;
int[][] matrix;
private int computeMinSum(int curX, int curY) {
int sum1, sum2;
if (curX == n - 1 && curY == n - 1) {
return matrix[curX][curY];
} else if (curX == n - 1) {
return (matrix[curX][curY] + computeMinSum(curX, curY + 1));
} else if (curY == n - 1) {
return (matrix[curX][curY] + computeMinSum(curX + 1, curY));
} else {
sum1 = computeMinSum(curX + 1, curY);
sum2 = computeMinSum(curX, curY + 1);
if (sum1 < sum2) {
return (matrix[curX][curY] + sum1);
} else {
return (matrix[curX][curY] + sum2);
}
}
}
public MinPathSum (String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
String matRow;
String[] params;
int i, j;
while ((line = br.readLine()) != null) {
n = Integer.valueOf(line).intValue();
matrix = new int[n][n];
for (i = 0; i < n; i++) {
matRow = br.readLine();
params = matRow.split(",");
for (j = 0; j < n; j++) {
matrix[i][j] = Integer.valueOf(params[j]).intValue();
}
}
System.out.println(computeMinSum(0, 0));
}
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Unsupported number of parameters passed. Exiting.");
System.exit(1);
}
MinPathSum mps = new MinPathSum(args[0]);
}
}