实现以下Matrix算法:
[img]http://dl.iteye.com/upload/attachment/464904/8b74cd03-5d8b-3f4e-bc35-b1e14efee297.jpg[/img]
第一种算法:
第二种算法:
一个 矩阵 的 算法 ,有 很多 种 算法,各个算法的执行效率都是不同的!算法 越先进,执行效率越高,但 这种 先进 算法的 诞生,需要认真观察和推敲才能得出!刚才,上面那个矩阵 的 算法,在都产生矩阵边长为:1000时,两种执行时间分别为:第一个是22毫秒,第二个是55毫秒,相差33毫秒。可见,相差的时间 还 是 蛮多的!
[img]http://dl.iteye.com/upload/attachment/464904/8b74cd03-5d8b-3f4e-bc35-b1e14efee297.jpg[/img]
第一种算法:
import java.io.IOException;
public class MatrixTest_2A {
public static void main(String[] args) throws IOException {
long time_begin = System.currentTimeMillis();
int[][] data = generateMatrix(6);
long time_end = System.currentTimeMillis();
System.out.println("程序执行时间:" + (time_end - time_begin));
for (int i = 0; i < data.length; i++) {
for (int m = 0; m < data[i].length; m++) {
if (data[i][m] == 0)
System.out.print("\t");
else
System.out.print(data[i][m] + "\t");
}
System.out.println();
}
}
private static int[][] generateMatrix(int n) {
int[][] ret = new int[n][n];
int maxValue = n * n;
int directionStatus = 1;
int rowIndex = 0;
int colIndex = 0;
int count = 0, temp = 0;
for (int i = 1; i <= maxValue; i++) {
ret[rowIndex][colIndex] = i;
if (directionStatus == 1) {
colIndex++;
temp = 0;
directionStatus = 2;
} else if (directionStatus == 2) {
rowIndex++;
if (temp < count && count != 0) {
directionStatus = 2;
temp++;
} else {
temp = 0;
directionStatus = 3;
}
} else if (directionStatus == 3) {
if (colIndex > 0)
colIndex--;
if (temp < count && count != 0) {
directionStatus = 3;
temp++;
} else {
temp = 0;
directionStatus = 4;
}
if (colIndex == 0)
count++;
} else if (directionStatus == 4) {
rowIndex = 0;
for (int j = 1; j <= count + 1; j++) {
colIndex++;
}
directionStatus = 2;
}
}
return ret;
}
}
第二种算法:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MatrixTest_2B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入您需要的矩阵的边长: ");
String inputString = br.readLine();
long time_begin = System.currentTimeMillis();
int len = Integer.parseInt(inputString);
int[][] a = new int[len + 1][len + 1];
for (int i = 1; i <= len; i++) {
for (int j = 1; j <= i; j++) {
a[i][j] = i * i - (j - 1);
}
for (int k = 1; k < i; k++) {
a[k][i] = (i - 1) * (i - 1) + k;
}
}
long time_end = System.currentTimeMillis();
System.out.println("程序执行时间:" + (time_end - time_begin));
// 输出矩阵
for (int i = 1; i <= len; i++) {
for (int j = 1; j <= len; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}
一个 矩阵 的 算法 ,有 很多 种 算法,各个算法的执行效率都是不同的!算法 越先进,执行效率越高,但 这种 先进 算法的 诞生,需要认真观察和推敲才能得出!刚才,上面那个矩阵 的 算法,在都产生矩阵边长为:1000时,两种执行时间分别为:第一个是22毫秒,第二个是55毫秒,相差33毫秒。可见,相差的时间 还 是 蛮多的!