给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。力扣题目
示例 1:
输入: n = 3
输出: [[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入: n = 1
输出: [[1]]
提示:
1 <= n <= 20
解题思路:这道题主要就是根据题意模拟画圈就行了, 定义4个边界位置
int left = 0, right =n-1; (按数组下标)
int top = 0, bottom =n-1;(按数组下标)
依次顺序是 左-->右(left-->right)依次赋值,结束后top++ 往下移
上-->下(top-->bottom)依次赋值,结束后right-- 往左移
右-->左(right-->left)依次赋值,结束后bottom-- 往上移
下-->上(bottom-->top)依次赋值,结束后left++ 往右移
class Solution {
public int[][] generateMatrix(int n) {
int matrix[][] =new int[n][n];
int left = 0, right =n-1;
int top = 0, bottom =n-1;
int count =1;
while(left <= right && top <= bottom){
//左-->右
for (int i = left;i<=right; i++){
matrix[top][i]= count++;
}
top++;
//从上到下
for (int i = top;i<=bottom; i++){
matrix[i][right]= count++;
}
right--;
for (int i = right;i >=left;i--){
matrix[bottom][i]= count++;
}
bottom--;
for (int i = bottom;i>=top;i--){
matrix[i][left]= count++;
}
left++;
}
return matrix;
}
}