给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
根据 《54.螺旋矩阵》进行改造,将1-n*n的数字按照一圈一圈的方向赋给新建的结果矩阵。
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int shang_row = 0;
int xia_row = n - 1;
int zou_col = 0;
int you_col = res[0].length - 1;
int j = 1, total = n * n;
while (j <= total) {
// 从左到右
for (int i = zou_col; i <= you_col; i++) res[shang_row][i] = j++;
shang_row++;
if (shang_row > xia_row) break;
// 从上到下
for (int i = shang_row; i <= xia_row; i++) res[i][you_col] = j++;
you_col--;
if (zou_col > you_col) break;
// 从右到左
for (int i = you_col; i >= zou_col; i--) res[xia_row][i] = j++;
xia_row--;
//从下到上
for (int i = xia_row; i >= shang_row; i--) res[i][zou_col] = j++;
zou_col++;
}
return res;
}
}