leetcode [59] Spiral Matrix II / Spiral Matrix II

Insert picture description here

Title address

https://leetcode-cn.com/problems/spiral-matrix-ii/

Ideas

Simulate the process of drawing a matrix clockwise

Fill up
row from left to right Fill right column from top to bottom
Fill down row from right to left
Fill left column from bottom to top

The most important idea in the simulation process is to keep the principle of drawing each side consistent, that is, the principle of closing left and right every time , if shown
Insert picture description here

Many students, the reason why they have been unable to write this problem all the time, the more and more messy the code is, because when drawing each side, there is no guarantee of uniform principles

For example: when simulating the top of the matrix, it is closed left and right, then when simulating the right column of the matrix, it is left closed and closed again, how can it not be messy

solution

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0)); // 使用vector定义一个二维数组
        int startx = 0, starty = 0; // 定义每循环一个圈的起始位置
        int loop = n / 2; // 每个圈循环几次
        int mid = n / 2; // 矩阵中间的位置,例如:n为3, 中间的位置就是(1,1),n为5,中间位置为(3, 3)
        int count = 1; // 用来计数
        int offset = 1; // 每一圈循环,需要偏移的位置
        int i,j;
        while (loop --) {
            i = startx;
            j = starty;

            // 下面开始的四个for就是模拟转了一圈
            // 模拟填充上行从左到右(左闭右开)
            for (j = starty; j < starty + n - offset; j++) {
                res[startx][j] = count++;
            }
            // 模拟填充右列从上到下(左闭右开)
            for (i = startx; i < startx + 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 += 2;
        }

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

I am a code junior. I have been engaged in technical research and development at BAT for many years. I use my spare time to repaint leetcode. For more original articles, please pay attention to "Code Random Notes".

Published 236 original articles · praised 251 · 270,000 views +

Guess you like

Origin blog.csdn.net/youngyangyang04/article/details/105422543