[CODE]
public class Matrix {
private int size = 0;
private int[][] converseMatrix;
private int[][] snakeMatrix;
private int[][] roundMatrix;
public Matrix(int size) {
this.size = size;
converseMatrix = new int[size][size];
snakeMatrix = new int[size][size];
roundMatrix = new int[size][size];
}
// 构造倒置矩阵
public void fillConverseMatrix() {
int total = size * size;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
converseMatrix[i][j] = total--;
}
}
}
// 构造蛇形矩阵
public void fillSnakeMatrix() {
int increase = 1, decrease = size*size;
for (int i = 0; i < size; i++) {
int m = 0, n = i;
for (int j = 0; j <= i; j++) {
if (i%2 == 0) {
snakeMatrix[m++][n--] = increase++;
snakeMatrix[size-1-m+1][size-1-n-1] = decrease--;
} else {
snakeMatrix[n--][m++] = increase++;
snakeMatrix[size-1-n-1][size-1-m+1] = decrease--;
}
}
}
}
// 构造回转矩阵
public void fillRoundMatrix() {
int roundLength = size, total = 1;
for (int i = 0; i < (size+1)/2; i++) {
for (int j=0; j < roundLength-1; j++) {
roundMatrix[j+i][i] = total++;
roundMatrix[size-1-i][j+i] = (total - 1) + (roundLength - 1);
roundMatrix[size-1-j-i][size-1-i] = (total - 1) + (roundLength - 1) * 2;
roundMatrix[i][size-1-j-i] = (total - 1) + (roundLength - 1) * 3;
}
roundLength -= 2;
total = roundMatrix[i][i+1] + 1;
}
if (size%2 == 1) {
roundMatrix[size/2][size/2] = size*size;
}
}
// 打印矩阵
public void print(int[][] matrix) {
int size = matrix.length;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.printf("[%2d]", matrix[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
Matrix test = new Matrix(5);
test.fillConverseMatrix();
test.fillSnakeMatrix();
test.fillRoundMatrix();
System.out.println("倒置矩阵:");
test.print(test.converseMatrix);
System.out.println("蛇形矩阵:");
test.print(test.snakeMatrix);
System.out.println("回转矩阵:");
test.print(test.roundMatrix);
}
}
[/CODE]