题目
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解法
class Solution {
public int[][] generateMatrix(int n) {
int[][] nums = new int[n][n];
nums[0][0] = 1;
if(n==1){
return nums;
}
top(nums,0,0,1,n*n);
return nums;
}
public void top(int[][] nums, int m, int n,int count,int end){
if(count==end){
return;
}
for(int i = n + 1; i < nums[0].length - m;i++){
nums[m][i] = ++count;
}
right(nums, m, nums[0].length - m -1, count, end);
}
public void right(int[][] nums, int m, int n,int count,int end){
if(count==end){
return;
}
for(int i = m + 1; i < nums.length - m; i++){
nums[i][n] = ++count;
}
bottom(nums, nums.length - m -1, n, count, end);
}
public void bottom(int[][] nums, int m, int n,int count,int end){
if(count==end){
return;
}
for(int i = n-1; i >= nums[0].length - n -1; i--){
nums[m][i] = ++count;
}
left(nums, m, nums[0].length - n -1, count, end);
}
public void left(int[][] nums, int m, int n,int count,int end){
if(count==end){
return;
}
for(int i = m-1; i >= nums.length - m ; i--){
nums[i][n] = ++count;
}
top(nums, nums[0].length - m, n, count, end);
}
}