题目描述
链接:https://leetcode-cn.com/problems/spiral-matrix-ii/
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
代码
public int[][] generateMatrix(int n) {
if (n <= 0) {
return null;
}
int[][] result = new int[n][n];
int totalCount = n * n;
int curFillCount = 1;
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
while (curFillCount <= totalCount) {
for (int i = left; i <= right && (curFillCount <= totalCount); i++) {
result[top][i] = curFillCount;
curFillCount ++;
}
top ++;
for (int i = top; i <= bottom && (curFillCount <= totalCount); i++) {
result[i][right] = curFillCount;
curFillCount ++;
}
right --;
for (int i = right; i >= left && (curFillCount <= totalCount); i--) {
result[bottom][i] = curFillCount;
curFillCount ++;
}
bottom --;
for (int i = bottom; i >= top && (curFillCount <= totalCount); i--) {
result[i][left] = curFillCount;
curFillCount ++;
}
left ++;
}
return result;
}
网友评论