问题描述
https://leetcode.com/problems/spiral-matrix-ii/#/description
Given an integer n
, generate a square matrix filled with elements from 1
to n^2
in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
输入一个数n
,输出从1
到n^2
的螺旋排序矩阵。
算法
直接按照从左到右、从上到下、从右到左、从下到上的顺序一个个数的填充数组即可。
代码
public int[][] generateMatrix(int n) {
if(n<=0) return new int[][]{};
int[][] res = new int[n][n];
// 开始填入数字
int rowBegin = 0, rowEnd = n-1;
int colBegin = 0, colEnd = n-1;
int index = 1;
while(rowBegin<=rowEnd || colBegin<=colEnd) {
// 从左到右
for(int i=colBegin;i<=colEnd;i++) {
res[rowBegin][i] = index++;
}
rowBegin++;
// 从上到下
for(int i=rowBegin;i<=rowEnd;i++) {
res[i][colEnd] = index++;
}
colEnd--;
// 从右到左
if(colEnd>=colBegin) {
for(int i=colEnd;i>=colBegin;i--) {
res[rowEnd][i] = index++;
}
}
rowEnd--;
// 从下到上
if(rowEnd >=rowBegin) {
for(int i=rowEnd;i>=rowBegin;i--) {
res[i][colBegin] = index++;
}
}
colBegin++;
}
return res;
}
LeetCode解题代码仓库:https://github.com/zgljl2012/leetcode-java