(LC)59. 螺旋矩阵 II

59. 螺旋矩阵 II

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

示例 1:

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

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

提示:

1 <= n <= 20

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

猜你喜欢

转载自blog.csdn.net/weixin_45567738/article/details/114899982