下班了换个eclipse写写,感觉还蛮好的。
这个循环的原理是,沿着矩阵的对角线,一层层向上计算,
发现这样的过程中,前面的条件都已经算好了。所以就不用递归了。
import java.util.ArrayList;
public class MatrixMultiply {
public MatrixMultiply() {
Matrix m1 = new Matrix(2, 5);
Matrix m2 = new Matrix(5, 100);
Matrix m3 = new Matrix(100, 4);
Matrix m4 = new Matrix(4, 50);
Matrix m5 = new Matrix(50, 6);
MList .add(m1);
MList .add(m2);
MList .add(m3);
MList .add(m4);
MList .add(m5);
for ( int i = 0; i < 5; i++)
for ( int j = 0; j < 5; j++) {
if (i >= j)
M [i][j] = 0;
else
M [i][j] = Integer. MAX_VALUE ;
}
}
private int [][] M = new int [5][5];
private ArrayList<Matrix> MList = new ArrayList<Matrix>();
public void getResult() {
// already fill the left-below half of the matrix, now fill the left-up
// part, the specialIndex is build by analysis matrix's structure
for ( int specialIndex = 1; specialIndex < 5; specialIndex++) {
int xIndex = 0;
int yIndex = xIndex + specialIndex;
while (yIndex < 5) {
M [xIndex][yIndex] = getMax(xIndex, yIndex);
yIndex++;
xIndex++;
}
}
System. out .println( "the optimized result is :" + M [0][4]);
}
private int getMax( int xIndex, int yIndex) {
if ( M [xIndex][yIndex] != Integer. MAX_VALUE )
return M [xIndex][yIndex];
else {
int finalMin = Integer. MAX_VALUE ;
int tempMin;
for ( int k = xIndex; k < yIndex; k++) {
tempMin = M [xIndex][k] + M [k + 1][yIndex]
+ MList .get(xIndex). orderX * MList .get(k). orderY
* MList .get(yIndex). orderY ;
if (finalMin > tempMin)
finalMin = tempMin;
}
return finalMin;
}
}
class Matrix {
public Matrix( int x, int y) {
orderX = x;
orderY = y;
}
int orderX ;
int orderY ;
}
}