螺旋矩阵(二)题解

螺旋矩阵(二)

在这里插入图片描述

分析:

按层模拟
可以将矩阵看成若干层,首先填入矩阵最外层元素,其次填入矩阵次外层的元素,直到填入矩阵最内层的元素。
在这里插入图片描述
对于每层,从左上方开始以顺时针的顺序填入所有元素。
假设当前层的左上角位于(top, left),右下角位于(bottom,right),按照如下顺序填入当前层的元素:

  1. 从左到右填入上侧元素,依次为(top,left)到(top,right);
  2. 从上到下填入右侧元素,依次为(top + 1,right)到(bottom,right);
  3. 从右到左填入底部元素,依次为(bottom,right - 1)到(bottom,left);
  4. 从下到上填入左侧元素,依次为(bottom - 1,left)到(top + 1,left)。

填完当前层的所有元素之后,将left和top分别增加1,right和bottom分别减1,进入下一层继续填入元素,知道填完所有元素为止。

代码

class Solution {
    
    
    public int[][] generateMatrix(int n) {
    
    
        int num = 1;
        int[][] matrix = new int[n][n];
        int top = 0, right = n - 1, bottom = n - 1, left = 0;
        while(left <= right && top <= bottom) {
    
    
            for(int col = top; col <= right; col++) {
    
    
                matrix[top][col] = num;
                num++;
            }
            for(int row = top + 1; row <= bottom; row++) {
    
    
                matrix[row][right] = num;
                num++;
            }
            for(int col = right - 1; col >= top; col--) {
    
    
                matrix[bottom][col] = num;
                num++;
            }
            for(int row = bottom - 1; row > top; row--) {
    
    
                matrix[row][left] = num;
                num++;
            }
            top++;
            right--;
            bottom--;
            left++;
        }
        return matrix;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45832482/article/details/122714522