实现以下Matrix算法:
[img]http://dl.iteye.com/upload/attachment/464717/88dd7581-e00c-3d2f-b77a-44aa604da6ea.jpg[/img]
[img]http://dl.iteye.com/upload/attachment/464717/88dd7581-e00c-3d2f-b77a-44aa604da6ea.jpg[/img]
import java.io.IOException;
public class MatrixTest_1 {
public static void main(String[] args) throws IOException {
int[][] data = generateMatrix(5);
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;
for (int i = 1; i <= maxValue; i++) {
ret[rowIndex][colIndex] = i;
if (rowIndex == n - 1)
break;
if (directionStatus == 1) {
if (rowIndex < n - 1) {
rowIndex++;
} else {
colIndex++;
}
directionStatus = 2;
} else if (directionStatus == 2) {
rowIndex--;
colIndex++;
if (rowIndex == 0) {
directionStatus = 3;
}
if (colIndex == n - 1) {
directionStatus = 3;
}
} else if (directionStatus == 3) {
if (colIndex < n - 1) {
colIndex++;
} else {
rowIndex++;
}
directionStatus = 4;
} else if (directionStatus == 4) {
rowIndex++;
colIndex--;
if (colIndex == 0) {
directionStatus = 1;
}
if (rowIndex == n - 1) {
directionStatus = 1;
}
}
}
return ret;
}
}