1-1:题目描述
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目理解:
比较好理解哈,按这个顺序去填写一个正方形数组。
1-2:解法
不涉及什么算法,单纯的用代码去模拟填充数组的这样一个思路。根据正常的逻辑,应该是按四条边,从外向里,从左到右,从上到下。如图:每次我们都提前算好一轮每条边上要遍历的值的数目。startX,startY分别是每一轮开始的坐标,比如第一轮startX=startY=0,第二轮startX=startY=1。这样我们就可以控制每一回的起点,方向,每天边遍历的数目啦!代码如下:
class Solution {
public int[][] generateMatrix(int n) {
int[][] nums = new int[n][n];
int count = 1;
int number = n - 1;
int startX = 0, startY = 0;
while (number > 0) { // 最好用number去控制,和螺旋矩阵I解法,保持一致。
int i = startX;
int j = startY;
while (j < startY + number) {
nums[i][j++] = count++;
}
// while (j < j+ number) {
// nums[i][j++] = count++;
// } 很容易写成这样!注意j也是跟着变的
while (i < startX + number) {
nums[i++][j] = count++;
}
while (j > startY) {
nums[i][j--] = count++;
}
while (i > startX) {
nums[i--][j] = count++;
}
startX++; // 坐标要跟着变,容易写着写着忘记了
startY++;
number -= 2;
}
if (n % 2 == 1) { // 如果是单数矩阵,中心位置要考虑到。
nums[n / 2][n / 2] = n * n;
}
return nums;
}
}
需要注意的是
- 下和左,这两条边的边界控制,用startX和startY控制好。
- 这里的这种边的处理方法,中心位置得最后处理。