【Likou】59. Spiral Matrix II <Simulation>

【Lee Button】59. Spiral Matrix II

give you a positive integer nnn , generate a list containing 1 ton 2 n^2n2 All elements, and the elements are spirally arranged in clockwise ordern × nn × nn×n square matrixmatrix matrixmatrix

Example 1:
insert image description here

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

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

Hint:
1 <= n <= 20

answer

Pay attention to the principle of loop invariance during each loop

  • Upstream from left to right (left closed right open)
  • Right column from top to bottom (left closed right open)
  • Downstream from right to left (left closed right open)
  • Left column from bottom to top (left closed right open)
public class Main {
    
    
    public int[][] generateMatrix(int n) {
    
    
        int[][] res = new int[n][n];
        // 定义每循环一个圈的起始位置
        int startx = 0, starty = 0;
        // 每个圈循环几次,例如 n为奇数 3,那么loop = 1 只是循环一圈,矩阵中间的值需要单独处理
        int loop = n / 2;
        // 矩阵中间的位置,例如:n为 3, 中间的位置就是(1,1),n为5,中间位置为(2, 2)
        int mid = n / 2;
        // 用来计数赋值
        int count = 1;
        // 需要控制每一条边遍历的长度,每次循环右边界收缩一位
        int offset = 1;
        int i, j;

        while ((loop--) > 0) {
    
    
            i = startx;
            j = starty;

            // 模拟填充上行从左到右(左闭右开)
            for (j = starty; j < n - offset; j++) {
    
    
                res[i][j] = count++;
            }
            // 模拟填充右列从上到下(左闭右开)
            for (i = startx; i < n - offset; i++) {
    
    
                res[i][j] = count++;
            }
            // 模拟填充下行从右到左(左闭右开)
            for (; j > starty; j--) {
    
    
                res[i][j] = count++;
            }
            // 模拟填充左列从下到上(左闭右开)
            for (; i > startx; i--) {
    
    
                res[i][j] = count++;
            }

            // 第二圈开始的时候,起始位置要各自加1, 例如:第一圈起始位置是(0, 0),第二圈起始位置是(1, 1)
            startx++;
            starty++;

            // offset 控制每一圈里每一条边遍历的长度
            offset += 1;
        }

        // 如果n为奇数的话,需要单独给矩阵最中间的位置赋值
        if ((n % 2) == 1) {
    
    
            res[mid][mid] = count;  //res[startx][starty] = count;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/132492124