59. Spiral Matrix II

59. Spiral Matrix II

Links to Links(opens new window)

Given a positive integer n, generate a square matrix containing all elements from 1 to n^2, and the elements are spirally arranged in clockwise order.

Example:

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

train of thought

Dichotomy: To write a correct dichotomy, you must adhere to the principle of loop invariance .

To solve this problem, we still need to adhere to the principle of loop invariance.

Simulate the process of drawing a matrix clockwise:

  • Fill upper row left to right
  • Fill right column top to bottom
  • Fill descending row from right to left
  • Fill left column from bottom to top

Draw it circle by circle from the outside to the inside.

class Solution {
    
    
    public int[][] generateMatrix(int n) {
    
    
        //左闭右开的原则
        int loop = 0; //控制循环次数
        int[][] result = new int[n][n];
        int start = 0; //每次循环的开始点(start, start)
        int count = 1; //定义填充的数字
        int i, j;
        // 判断边界后,loop从1开始; 
        // n/2: 每个圈循环几次,例如n为奇数3,那么loop = 1 只是循环一圈,矩阵中间的值需要单独处理
        while(loop++ < n/2){
    
     
            // 模拟上侧从左到右
            for(j = start; j < n - loop; j++){
    
    
                result[start][j] = count++;
            }

            // 模拟右侧从上到下
            for(i = start; i < n - loop; i++){
    
    
                result[i][j] = count++;
            }
            
            // 模拟下侧从右到左
            for(; j >= loop; j--){
    
    
                result[i][j] = count++;
            }

            // 模拟左侧从下到上
            for(; i >= loop; i--){
    
    
                result[i][j] = count++;
            }
            start++;
        }
        // 如果n为奇数的话,需要单独给矩阵最中间的位置赋值
        if (n % 2 == 1) {
    
    
            result[start][start] = count;
        }

        return result;
    }
}
  • Time complexity O(n^2): Simulate the time to traverse a two-dimensional matrix
  • Space complexity O(1)

Guess you like

Origin blog.csdn.net/qq_41883610/article/details/129913667