问题

给定一个正整数 n,生成一个包含 1 到 leetcode-59:螺旋矩阵Ⅱ - 图1 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵

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

思路

对于每层,从左上方开始以顺时针的顺序填入所有元素。假设当前层的左上角位于leetcode-59:螺旋矩阵Ⅱ - 图2,右下角位于 leetcode-59:螺旋矩阵Ⅱ - 图3,按照如下顺序填入当前层的元素:
从左到右填入上侧元素,依次为leetcode-59:螺旋矩阵Ⅱ - 图4leetcode-59:螺旋矩阵Ⅱ - 图5
从上到下填入右侧元素,依次为leetcode-59:螺旋矩阵Ⅱ - 图6leetcode-59:螺旋矩阵Ⅱ - 图7
如果leetcode-59:螺旋矩阵Ⅱ - 图8leetcode-59:螺旋矩阵Ⅱ - 图9,则从右到左填入下侧元素,依次为leetcode-59:螺旋矩阵Ⅱ - 图10leetcode-59:螺旋矩阵Ⅱ - 图11,以及从下到上填入左侧元素,依次为leetcode-59:螺旋矩阵Ⅱ - 图12leetcode-59:螺旋矩阵Ⅱ - 图13
填完当前层的元素之后,将leetcode-59:螺旋矩阵Ⅱ - 图14leetcode-59:螺旋矩阵Ⅱ - 图15分别增加leetcode-59:螺旋矩阵Ⅱ - 图16,将leetcode-59:螺旋矩阵Ⅱ - 图17leetcode-59:螺旋矩阵Ⅱ - 图18分别减少leetcode-59:螺旋矩阵Ⅱ - 图19,进入下一层继续填入元素,直到填完所有元素为止

方法一

  1. class Solution {
  2. public int[][] generateMatrix(int n) {
  3. int num = 1;
  4. int[][] matrix = new int[n][n];
  5. int left = 0, right = n - 1, top = 0, bottom = n - 1;
  6. while (left <= right && top <= bottom) {
  7. for (int column = left; column <= right; column++) {
  8. matrix[top][column] = num;
  9. num++;
  10. }
  11. for (int row = top + 1; row <= bottom; row++) {
  12. matrix[row][right] = num;
  13. num++;
  14. }
  15. if (left < right && top < bottom) {
  16. for (int column = right - 1; column > left; column--) {
  17. matrix[bottom][column] = num;
  18. num++;
  19. }
  20. for (int row = bottom; row > top; row--) {
  21. matrix[row][left] = num;
  22. num++;
  23. }
  24. }
  25. left++;
  26. right--;
  27. top++;
  28. bottom--;
  29. }
  30. return matrix;
  31. }
  32. }
  • 时间复杂度:O(n^2)
  • 空间复杂度:O(1)。除了返回的矩阵以外,空间复杂度是常数

方法二

思路

边界条件很多,每画一条边都要坚持一致的左闭右开或者左开右闭原则
image.png

  1. package leetcode;
  2. import java.util.Arrays;
  3. public class leetcode_59_1 {
  4. public int[][] generateMatrix(int n) {
  5. int[][] res = new int[n][n];
  6. int up = 0, down = n - 1, left = 0, right = n - 1, index = 1;
  7. while(index <= n * n){
  8. for(int i = left; i <= right; i++){
  9. res[up][i] = index++;
  10. }
  11. up++;
  12. for(int i = up; i <= down; i++){
  13. res[i][right] = index++;
  14. }
  15. right--;
  16. for(int i = right; i >= left; i--){
  17. res[down][i] = index++;
  18. }
  19. down--;
  20. for(int i = down; i >= up; i--){
  21. res[i][left] = index++;
  22. }
  23. left++;
  24. }
  25. return res;
  26. }
  27. public static void main(String[] args){
  28. leetcode_59_1 lt = new leetcode_59_1();
  29. int[][] res = lt.generateMatrix(3);
  30. System.out.println(Arrays.deepToString(res));
  31. }
  32. }

leetcode-59:螺旋矩阵Ⅱ - 图21——打印多维数组