59_螺旋矩阵II

难度:中等

题目

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

示例

示例一:

img

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

示例二:

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

提示

  • 1 <= n <= 20

解题

模拟矩阵,初始位置为左上角,初始方向为向右,超出边界或者到已访问过的位置时修改方向,按照右下左上的顺序改变方向。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public int[][] generateMatrix(int n){
int[][] ans = new int[n][n];
int max = n * n;
int curr = 1;
int row = 0, col = 0;
// 右、下、左、上方向
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
int directionIndex = 0;
while (curr<=max){
ans[row][col] = curr;
curr++;
int nextRow = row + directions[directionIndex][0], nextCol = col + directions[directionIndex][1];
// 超出边界或者到已访问过的地方
if (nextRow<0||nextRow>=n||nextCol<0||nextCol>=n||ans[nextRow][nextCol]!=0){
// 改变方向
directionIndex = (directionIndex+1)%4;
}
row = row + directions[directionIndex][0];
col = col + directions[directionIndex][1];
}
return ans;
}