【LeetCode】59. 螺旋矩阵 II (Java代码)
来源:力扣(LeetCode)
题目链接:https://leetcode.cn/problems/spiral-matrix-ii
难度:中等
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
题解
该题没有什么算法可言,使用模拟法即可。
保证循环不变量,遍历每一条边时
- 左闭右开
- 左闭右闭
左闭右开版本
class Solution {
public int[][] generateMatrix(int n) {
//存入的数
int index = 1;
//每一次循环起始的x,y
int start = 0;
//循环的次数 不信自己找例子试一试
int loop = n / 2;
int i,j;
//遍历每一条边的终止下标
int offSet = 1;
int[][] ans = new int[n][n];
while(loop-- > 0) {
//更新开始遍历的位置
i = j = start;
//从左往右
for(; j < n - offSet; j++)
ans[i][j] = index++;
//从上往下
for(; i < n - offSet; i++)
ans[i][j] = index++;
//下面两种情况的终止条件是下标大于起始位置
//从右往左
for(; j > start; j--)
ans[i][j] = index++;
//从下往上
for(; i > start; i--)
ans[i][j] = index++;
//每循环一轮 更新起始位置 和 终止条件
start++;
offSet++;
}
//如果n是奇数 最中间的位置由于offSet 和 循环次数loop的限制无法存入 进行特殊处理
if(n % 2 != 0)
ans[start][start] = index;
return ans;
}
}
左闭右闭版本
class Solution {
public int[][] generateMatrix(int n) {
//数组存储的数
int index = 1;
//存储的最大值
int max = n * n;
int i = 0;
int j = 0;
//终止条件
int offSet = 0;
int[][] ans = new int[n][n];
while(index <= max) {
//从左到右
while(j < n - offSet) {
ans[i][j++] = index++;
}
//此时j越界 则j减一 该行最后一个位置已经存入数 则i加1
j--;
i++;
//从上往下
while(i < n - offSet) {
ans[i++][j] = index++;
}
//此时i越界 则i减一 该列最后一个位置已经存入数 则j减一
i--;
j--;
//从右往左
while(j >= offSet) {
ans[i][j--] = index++;
}
//此时j越界 则j加一 该行第一个位置已存入数 则i减一
j++;
i--;
//从右往左后 终止条件要改变 因为从下往上的那一列的第一个已经存入数
offSet++;
//从下往上
while(i >= offSet) {
ans[i--][j] = index++;
}
//更新起始位置
i++;
j++;
}
return ans;
}
}