/**
* Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
* For example,
* Given n =3,
* You should return the following matrix:
* [
* [ 1, 2, 3 ],
* [ 8, 9, 4 ],
* [ 7, 6, 5 ]
* ]
*
* 给定一个整数n,生成一个以螺旋顺序填充从1到n 2元素的正方形矩阵。
* 例如,
* 如果n=3,
* 您应该返回以下矩阵:
* You should return the following matrix:
* [
* [ 1, 2, 3 ],
* [ 8, 9, 4 ],
* [ 7, 6, 5 ]
* ]
*/
/**
* Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
* For example,
* Given n =3,
* You should return the following matrix:
* [
* [ 1, 2, 3 ],
* [ 8, 9, 4 ],
* [ 7, 6, 5 ]
* ]
*
* 给定一个整数n,生成一个以螺旋顺序填充从1到n 2元素的正方形矩阵。
* 例如,
* 如果n=3,
* 您应该返回以下矩阵:
* You should return the following matrix:
* [
* [ 1, 2, 3 ],
* [ 8, 9, 4 ],
* [ 7, 6, 5 ]
* ]
*/
public class Main46 {
public static void main(String[] args) {
int n = 5;
int[][] matrix = generateMatrix(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 static int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int count = 1;
int start = 0;
while (count <= n*n) {
int endX = n-1-start; //列
int endY = n-1-start; //行
for (int i=start;i<=endX;i++) {
matrix[start][i] = count;
count++;
}
for (int i=start+1;i<=endY;i++) {
matrix[i][endY] = count;
count++;
}
for (int i=endX-1;i>=start && endY>start;i--) {
matrix[endY][i] = count++;
}
for (int i=endY-1;i>=start+1 && endX>start;i--) {
matrix[i][start] = count++;
}
start++;
}
return matrix;
}
}