【刷题日记】数组-螺旋矩阵II-L59-Medium
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
思路
- 直接模拟过程,顺时针方向。用二维数组
directions
保存顺时针方向,当超过范围或遇到访问过元素时,改变方向
学习点
directions[0]、[1]、[2]、[3]
分别表示 4 个方向,二维分别为 row
和 col
代码
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
| class Solution { public: vector<vector<int>> generateMatrix(int n) { int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int max_num = n * n; vector<vector<int>> spiral_metrix(n, vector<int>(n, 0)); int curr_num = 1; int row = 0, col = 0; int curr_direct = 0; while (curr_num <= max_num) { spiral_metrix[row][col] = curr_num; ++curr_num; int next_row = row + directions[curr_direct][0]; int next_col = col + directions[curr_direct][1]; if (next_row >= n || next_col >= n || next_row < 0 || next_col < 0 || spiral_metrix[next_row][next_col] != 0) { curr_direct = (curr_direct + 1) % 4; } next_row = row + directions[curr_direct][0]; next_col = col + directions[curr_direct][1];
row = next_row; col = next_col; }
return spiral_metrix; } };
|