题目描述
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 ]
]
- 思路
螺旋保存二维数组值。
设置上、右、下、左四个变量,然后每次循环填数并更新对应的变量即可。
public class Solution {
public int[][] generateMatrix(int n) {
int[][] map = new int[n][n];
if(n <= 0)
return map;
int num = 1;
int up = 0;
int right = n-1;
int down = n-1;
int left = 0;
while(num <= n*n){
for(int i=up; i<=right; i++){
map[up][i] = num;
num ++;
}
up ++;
for(int i=up; i<=down; i++){
map[i][right] = num;
num ++;
}
right --;
for(int i=right; i>=left; i--){
map[down][i] = num;
num ++;
}
down --;
for(int i=down; i>=up; i--){
map[i][left] = num;
num ++;
}
left ++;
}
return map;
}
}