题目:
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解答:
/**
实现思路:给定四个边界,left = 0,right = n-1, top = 0,bottom = n-1,
然后每次进行四遍循环,
(top)left->right 循环结束后top+1
(right)top->bottom 循环结束后right-1
(bottom)right->left 循环结束后bottom-1
(left)bottom->top 循环结束后left+1
这题目和54题一模一样
**/
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int top = 0;
int botton = n - 1;
int left = 0;
int right = n - 1;
int index = 1;
while(top < botton && left < right){
for(int i = left; i < right; i++) res[top][i] = index++;
for(int j = top; j < botton; j++) res[j][right] = index++;
for(int k = right; k > left; k--) res[botton][k] = index++;
for(int m = botton; m > top; m--) res[m][left] = index++;
left++;
right--;
top++;
botton--;
}
if(top == botton){
for(int i = left; i <= right; i++){
res[top][i] = index++;
}
}else if(left == right){
for(int i = top; i <= botton; i++){
res[i][left] = index++;
}
}
return res;
}
}