给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int[][] generateMatrix(int n) {
int[][] ret = new int[n][n];
int idx = 1;
int row1 = 0, col1 = 0;
int row2 = n - 1, col2 = n - 1;
while (row1 <= row2 && col1 <= col2) {
if (row1 == row2) {
for (int i = col1; i <= col2; ++i) {
ret[row1][i] = idx++;
}
} else if (col1 == col2) {
for (int i = row1; i <= row2; ++i) {
ret[i][col1] = idx++;
}
} else {
for (int i = col1; i < col2; ++i) {
ret[row1][i] = idx++;
}
for (int i = row1; i < row2; ++i) {
ret[i][col2] = idx++;
}
for (int i = col2; i > col1; --i) {
ret[row2][i] = idx++;
}
for (int i = row2; i > row1; --i) {
ret[i][col1] = idx++;
}
}
row1++;
col1++;
row2--;
col2--;
}
return ret;
}
}