用Java编写实现
打印n阶的如下矩阵(矩阵中数字是从中间顺时针向外旋转的)[时间:20分钟以内]
n=3
7 8 9
6 1 2
5 4 3
n=4
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13
n=5
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
源代码如下:
public class MyMatrix {
public String[] direct = new String[] { "left", "down", "right", "up" };
public int n = 5;
public void print(int[][] matrix, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public void createMatrix() {
int seed = 1;
int[][] matrix = new int[n][n];
int cx = n % 2 == 0 ? n/2 : (n / 2) + 1;
int cy = n % 2 == 0 ? n/2 : (n / 2) + 1;
int posX = cx - 1;
int posY = cy - 1;
matrix[posY][posX] = seed;
int step=1;
int count=1;
while(true){
//step++;
for (int i = 0; i < direct.length; i++) {
String dir = direct[i];
for (int j = 0; j < step; j++) {
while (matrix[posY][posX] != 0) {
if (dir == "left") {
posX++;
if (posX > n - 1){
print(matrix, n);
return;
}
}
if (dir == "down") {
posY++;
if (posY > n - 1){
print(matrix, n);
return;
}
}
if (dir == "right") {
posX--;
if (posX < 0){
print(matrix, n);
return;
}
}
if (dir == "up") {
posY--;
if (posY < 0){
print(matrix, n);
return;
}
}
}
matrix[posY][posX] = ++seed;
}
if(count%2==0){
step++;
}
count++;
}
}
}
public static void main(String[] args) {
MyMatrix matrix = new MyMatrix();
matrix.createMatrix();
}
}