59. 螺旋矩阵 II(简单)

1,问题描述

59. 螺旋矩阵 II

难度:中等

给你一个正整数 n ,生成一个包含 1n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

示例 1:

img

1
2
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

1
2
输入:n = 1
输出:[[1]]

提示:

  • 1 <= n <= 20

2,初步思考

​ 规则很简单,直接模拟它的规则就行了

3,代码处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class _59螺旋矩阵II {

// 解法1:直接暴力处理即可(规则生成)
public int[][] generateMatrix(int n) {
int counter = 1;
int[][] res = new int[n][n];
int i = 0, j = 0;

int target = 0;// 0 向右,1向下,2向左,3向上
int abs = n;
int tempCounter = 0;
while (counter <= n * n) {
res[j][i] = counter++;// 前行后列!!!
tempCounter++;
switch (target) {
case 0:// 向右
tempCounter %= abs;
if (tempCounter == 0) {// 换方向
abs--;
target = (target + 1) % 4;
j++;
} else {
i++;
}
break;
case 1:// 向下
tempCounter %= abs;
if (tempCounter == 0) {
target = (target + 1) % 4;
i--;
} else {
j++;
}
break;
case 2:// 向左
tempCounter %= abs;
if (tempCounter == 0) {
abs--;
target = (target + 1) % 4;
j--;
} else {
i--;
}
break;
case 3:// 向上
tempCounter %= abs;
if (tempCounter == 0) {
target = (target + 1) % 4;
i++;
} else {
j--;
}
break;
}
}
return res;
}

public static void main(String[] args) {
_59螺旋矩阵II spiralMatrixII = new _59螺旋矩阵II();
int[][] ints = spiralMatrixII.generateMatrix(3);
System.out.println();
}
}
/**
* 1,8,7
* 2,9,6
* 3,4,5
*/

参考链接:

https://leetcode.cn/problems/spiral-matrix-ii/description/?envType=company&envId=bytedance&favoriteSlug=bytedance-thirty-days