Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]在spiral matrix那道题上稍微改动一下就可以通过
Source
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n]; //填数的话尺寸要确定到第二维
if(n == 0) return matrix;
int cycle = n / 2;
int p = 1;
for(int i = 0; i < cycle; i++){ //***
for(int j = i; j < n - i; j++){
matrix[i][j] = p++;
}
for(int j = i + 1; j < n - i; j++){
matrix[j][n - 1 - i] = p++;
}
for(int j = n - i - 2; j >= i; j--){
matrix[n - 1 - i][j] = p++;
}
for(int j = n - 2 - i; j > i; j--){
matrix[j][i] = p++;
}
}
if(p <= n * n){ //奇数行 注意只有一行和一列的情况
for(int j = cycle ; j < n - cycle ; j++){
matrix[cycle][j] = p++;
}
for(int j = cycle + 1; j < n - cycle; j++){
matrix[j][cycle] = p++;
}
}
return matrix;
}
Test
public static void main(String[] args){
int n = 3;
int[][] st = new Solution().generateMatrix(n);
for(int i = 0; i < st.length; i++){
for(int j = 0; j < st[0].length; j++){
System.out.print(st[i][j] + " "); //打空格注意用双引号,用单引号容易转换为char相加后的数值
}
}
}