1,问题描述
59. 螺旋矩阵 II
难度:中等
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:

1 2
| 输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
|
示例 2:
提示:
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 {
public int[][] generateMatrix(int n) { int counter = 1; int[][] res = new int[n][n]; int i = 0, j = 0;
int target = 0; 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(); } }
|
参考链接:
https://leetcode.cn/problems/spiral-matrix-ii/description/?envType=company&envId=bytedance&favoriteSlug=bytedance-thirty-days