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

示例 1:

螺旋矩阵Ⅱ-59 - 图1

  1. Input: n = 3
  2. Output: [[1,2,3],[8,9,4],[7,6,5]]

示例 2:

  1. Input: n = 1
  2. Output: [[1]]

提示:

  • 1 ≤ n ≤ 20;

思路

学习Krahets神的思路,他的边界处理很优秀。

示意图如下:

螺旋矩阵Ⅱ-59 - 图2

我们新建4个边界:top_edge = 0bottom_edge = n - 1left_edge = 0right_edge = n - 1,模拟整个填数的过程。用while()循环来填数,第一个数是1,当我们填数填到n*n就停止。

while()循环里分四个步骤:

  1. 从左往右填数,填完后top_edge += 1
  2. 从上往下填数,填完后right_edge -=1
  3. 从右往左填数,填完后bottom_edge -=1
  4. 从下往上填数,填完后left_edge += 1

代码

Cpp:

  1. // 0ms, 6.3MB
  2. class Solution {
  3. public:
  4. vector<vector<int>> generateMatrix(int n) {
  5. vector<vector<int>> matrix(n, vector<int>(n));
  6. int left_edge = 0;
  7. int right_edge = n - 1;
  8. int top_edge = 0;
  9. int bottom_edge = n - 1;
  10. int num = 1, target = n * n;
  11. while(num <= target) {
  12. // left to right
  13. for(int i = left_edge; i <= right_edge; i++)
  14. matrix[top_edge][i] = num ++;
  15. top_edge += 1;
  16. // top tp down
  17. for(int i = top_edge; i <= bottom_edge; i++)
  18. matrix[i][right_edge] = num ++;
  19. right_edge -= 1;
  20. // right to left
  21. for(int i = right_edge; i >= left_edge; i--)
  22. matrix[bottom_edge][i] = num ++;
  23. bottom_edge -= 1;
  24. // bottom to top
  25. for(int i = bottom_edge; i >= top_edge; i--)
  26. matrix[i][left_edge] = num ++;
  27. left_edge += 1;
  28. }
  29. return matrix;
  30. }
  31. };

Rust:

  1. // 0ms, 2.1MB
  2. impl Solution {
  3. pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> {
  4. let n = n as usize;
  5. let mut matrix: Vec<Vec<i32>> = vec![ vec![0; n]; n ];
  6. if n == 1 {
  7. matrix[0][0] = 1;
  8. return matrix;
  9. }
  10. let mut top_edge = 0;
  11. let mut bottom_edge = n - 1;
  12. let mut left_edge = 0;
  13. let mut right_edge = n - 1;
  14. let mut num: i32 = 1;
  15. let target: i32 = (n * n) as i32;
  16. let mut i = 0;
  17. while num <= target {
  18. // Left to right
  19. i = left_edge;
  20. while i <= right_edge {
  21. matrix[top_edge][i] = num;
  22. num += 1;
  23. i += 1;
  24. }
  25. top_edge += 1;
  26. // Top to bottom
  27. i = top_edge;
  28. while i <= bottom_edge {
  29. matrix[i][right_edge] = num;
  30. num += 1;
  31. i += 1;
  32. }
  33. right_edge -= 1;
  34. // Right to left
  35. i = right_edge;
  36. while i >= left_edge {
  37. matrix[bottom_edge][i] = num;
  38. num += 1;
  39. if i == 0 { break; }
  40. i -= 1;
  41. }
  42. bottom_edge -= 1;
  43. // Bottom to top
  44. i = bottom_edge;
  45. while i >= top_edge {
  46. matrix[i][left_edge] = num;
  47. num += 1;
  48. if i == 0 { break; }
  49. i -= 1;
  50. }
  51. left_edge += 1;
  52. }
  53. matrix
  54. }
  55. }