[Leetcode] 59. Spiral-matrix-ii (simulation) [medium]

link

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

time consuming

Problem solving: 7 min
Problem solving: 11 min

Title

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.

prompt:

  • 1 <= n <= 20

Ideas

It is exactly the same as [leetcode] 54. Spiral-matrix (simulation) [medium] . The difference between the two questions is basically the input of 54 into the output, and then the matrix is ​​simplified to a square matrix, which is simpler , Just change it on the basis of 54 code.

Set a variable from 1 to n 2 n^2n2 . For this variable:

Go in a circle from the outside to the inside, and treat each circle as a loop knot. A circle includes the upper, right, lower, and left parts, and the assignments are traversed separately. It should be noted that when there is only one row or one column, You need to make a special judgment and only traverse the upper or right side. If you traverse more, the parallel position will be repeated. There is also the first part to traverse the entire line, otherwise it will not be traversed when there is only one element.

Time complexity: O (n 2) O(n^2)O ( n2)

AC code

class Solution {
    
    
public:
    vector<vector<int>> generateMatrix(int n) {
    
    
        vector<vector<int>> matrix(n, vector<int>(n, 0));
        int cnt = (n+1)/2;
        int num = 0;
        for(int i = 0; i < cnt; ++i) {
    
    
            for(int j = i; j <= n-i-1; ++j) {
    
    
                matrix[i][j] = ++num;
            }
            for(int j = i+1; j <= n-i-1; ++j) {
    
    
                matrix[j][n-i-1] = ++num;
            }
            if(n-2*i > 1) {
    
    
                for(int j = n-i-2; j >= i; --j) {
    
    
                    matrix[n-i-1][j] = ++num;
                }
                for(int j = n-i-2; j > i; --j) {
    
    
                    matrix[j][i] = ++num;
                }
            }
        }
        return matrix;
    }
};

Guess you like

Origin blog.csdn.net/Krone_/article/details/114867081