螺旋矩阵
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
(上述题目来源于LeetCode)
解法
class Solution {
public int[][] generateMatrix(int n) {
//用边界来限制元素按顺时针排列
int[][] matrix = new int[n][n];
//定义上下左右四个边界
int top = 0;
int bottom = n - 1;
int right = n - 1;
int left = 0;
int count = 1;
while(count <= n*n){
//从左边界出发,到右边界
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;
}
}