Problem 82
Path sum: three ways
NOTE: This problem is a more challenging version of Problem 81.
The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994.
131 | 673 | 234 | 103 | 18 |
201 | 96 | 342 | 965 | 150 |
630 | 803 | 746 | 422 | 111 |
537 | 699 | 497 | 121 | 956 |
805 | 732 | 524 | 37 | 331 |
Find the minimal path sum, in matrix.txt (right click and “Save Link/Target As…”), a 31K text file containing a 80 by 80 matrix, from the left column to the right column.
路径和:三个方向
注意:这是第81题的一个更具挑战性的版本。
在如下的5乘5矩阵中,从最左栏任意一格出发,始终只向右、向上或向下移动,到最右栏任意一格结束的最小路径和为994,由标注红色的路径给出。
131 | 673 | 234 | 103 | 18 |
201 | 96 | 342 | 965 | 150 |
630 | 803 | 746 | 422 | 111 |
537 | 699 | 497 | 121 | 956 |
805 | 732 | 524 | 37 | 331 |
在这个31K的文本文件matrix.txt(右击并选择“目标另存为……”)中包含了一个80乘80的矩阵,求出从最左栏到最右栏的最小路径和。
package projecteuler;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Stack;
import junit.framework.TestCase;
public class Prj82 extends TestCase {
public static final String PATH = "E:\\whua\\mathWorkspace\\test_jgraph\\src\\projecteuler\\Prj81.txt";
public static final int ROW_COUNT = 80;
public static int[][] DATA = null;
/**
* 要跑40分钟,fuck
*/
public void testPathSumThreeWays() {
DijkStraShortPath shortPath = new DijkStraShortPathImpl();
int max = Integer.MAX_VALUE;
int iID = 0;
int jID = 0;
for (int i = 0; i < ROW_COUNT; i++) {
for (int j = 0; j < ROW_COUNT; j++) {
shortPath.findPath(i * ROW_COUNT);
int val = (int) shortPath.trace(i * ROW_COUNT, j * ROW_COUNT
+ ROW_COUNT - 1);
if (val < max) {
iID = i * ROW_COUNT;
jID = j * ROW_COUNT + ROW_COUNT - 1;
max = val;
}
}
}
String fstr = "sum=%d, start=(%d,%d) --->(%d,%d)";
fstr = String.format(fstr, max, iID * ROW_COUNT, 0, iID, jID);
System.out.println(fstr);
}
public static class DijkStraShortPathImpl extends DijkStraShortPath {
class Vertex implements IVertex {
private int m;
@Override
public String toString() {
return "Vertex [m=" + m + ", n=" + n + "]";
}
private int n;
private int rowCount;
public Vertex(int m, int n, int Col) {
this.m = m;
this.n = n;
this.rowCount = Col;
}
@Override
public int getVertexId() {
return m * rowCount + n;
}
@Override
public Object getDescrp() {
return "(" + m + "," + n + ")";
}
}
@Override
public IVertex id2Vertex(int id) {
return new Vertex(id / ROW_COUNT, id % ROW_COUNT, ROW_COUNT);
}
@Override
public void createEdge() {
int[][] data = readStr();
int rowCount = data[0].length;
int numOfVertex = rowCount * rowCount;
this.flag = new boolean[numOfVertex];
this.edge = new int[numOfVertex][numOfVertex];
for (int i = 0; i < numOfVertex; i++) {
for (int j = 0; j < numOfVertex; j++) {
edge[i][j] = MAX_MASK;
}
}
// ↓
for (int i = 0; i < rowCount - 1; i++) {
for (int j = 0; j < rowCount; j++) {
edge[i * rowCount + j][(i + 1) * rowCount + j] = data[i][j]
+ data[i + 1][j];
}
}
// →
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < rowCount - 1; j++) {
edge[i * rowCount + j][i * rowCount + j + 1] = data[i][j]
+ data[i][j + 1];
}
}
// ↑
for (int i = 1; i < rowCount; i++) {
for (int j = 0; j < rowCount; j++) {
edge[i * rowCount + j][(i - 1) * rowCount + j] = data[i][j]
+ data[i - 1][j];
}
}
}
@Override
public Object trace(int startId, int findId) {
System.out.println("START++++");
int sum = 0;
sum += DATA[findId / ROW_COUNT][findId % ROW_COUNT];
IVertex vt = path[findId];
Stack<IVertex> stack = new Stack<IVertex>();
while (vt.getVertexId() != startId) {
stack.push(vt);
int id = vt.getVertexId();
sum += DATA[id / ROW_COUNT][id % ROW_COUNT];
vt = path[vt.getVertexId()];
}
sum += DATA[startId / ROW_COUNT][startId % ROW_COUNT];
System.out.println(id2Vertex(findId));
// Object[] objArr = stack.toArray();
// for (Object o : objArr) {
// System.out.println(o);
// }
System.out.println(path[startId]);
System.out.println("END++++");
System.out.println("sum=" + sum);
return sum;
}
}
public interface IVertex {
int getVertexId();
Object getDescrp();
}
public static abstract class DijkStraShortPath {
public static final int MAX_MASK = Integer.MAX_VALUE;
protected int[][] edge;
protected boolean[] flag;
protected IVertex[] path;
public abstract void createEdge();
public abstract IVertex id2Vertex(int id);
public abstract Object trace(int startId, int endId);
public int[] findPath(int startId) {
createEdge();
path = new IVertex[flag.length];
IVertex start = id2Vertex(startId);
path[startId] = start;
int numOfVertex = flag.length;
int[] dist = new int[numOfVertex];
for (int i = 0; i < dist.length; i++) {
dist[i] = edge[start.getVertexId()][i];
}
for (int i = 0; i < dist.length; i++) {
if (i != startId && edge[startId][i] != MAX_MASK) {
path[i] = id2Vertex(startId);
}
}
dist[startId] = 0;
flag[startId] = true;
for (;;) {
int minId = -1;
int minVal = MAX_MASK;
for (int i = 0; i < flag.length; i++) {
if (!flag[i]) {
if (dist[i] < minVal) {
minVal = dist[i];
minId = i;
}
}
}
if (minId == -1) {
break;
}
for (int j = 0; j < flag.length; j++) {
if (j != minId && !flag[j] && edge[minId][j] != MAX_MASK
&& edge[minId][j] + dist[minId] < dist[j]) {
dist[j] = edge[minId][j] + dist[minId];
path[j] = id2Vertex(minId);
}
}
flag[minId] = true;
}
return dist;
}
}
static int[][] readStr() {
if (DATA != null) {
return DATA;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(PATH), "utf8"));
int[][] ret = new int[ROW_COUNT][ROW_COUNT];
int count = 0;
String str = "";
while ((str = reader.readLine()) != null) {
String[] strs = str.split(",");
for (int i = 0; i < strs.length; i++) {
ret[count][i] = Integer.parseInt(strs[i]);
}
count++;
}
reader.close();
DATA = ret;
return ret;
// int[][] ret = new int[][] { { 131, 673, 234, 103, 18 },
// { 201, 96, 342, 965, 150 }, { 630, 803, 746, 422, 111 },
// { 537, 699, 497, 121, 956 }, { 805, 732, 524, 37, 331 } };
//
// DATA = ret;
// return ret;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}