版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82831145
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/spiral-matrix-ii/description/
题目描述:
知识点:数组
思路:实时更新螺旋的四个边界left、right、top、bottom的值
本题的思路和LeetCode054——螺旋矩阵的思路二一模一样,因此不再过多分析。
JAVA代码:
public class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int num = 1;
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
while(left <= right && top <= bottom) {
for (int i = left; i <= right; i++) {
result[top][i] = num++;
}
top++;
for (int i = top; i <= bottom; i++) {
result[i][right] = num++;
}
right--;
if(top <= bottom) {
for (int i = right; i >= left; i--) {
result[bottom][i] = num++;
}
bottom--;
}
if(left <= right) {
for (int i = bottom; i >= top; i--) {
result[i][left] = num++;
}
left++;
}
}
return result;
}
}
LeetCode解题报告: