(LC) 59. Spiral Matrix II

59. Spiral Matrix II

Give you a positive integer n to generate an nxn square matrix matrix containing all elements from 1 to n2, and the elements are spirally arranged in a clockwise order.

Example 1:

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

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

prompt:

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;
        
    }

Guess you like

Origin blog.csdn.net/weixin_45567738/article/details/114899982