c_cpp [螺旋矩阵II]:给定整数n,生成以螺旋顺序填充1到n2的元素的方阵。例如,给定n =

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp [螺旋矩阵II]:给定整数n,生成以螺旋顺序填充1到n2的元素的方阵。例如,给定n =相关的知识,希望对你有一定的参考价值。

// give a number, generate a 2D matrix
vector<vector<int>> generate_spiral_matrix(int n) {
    vector<vector<int>> M(n, vector<int>(n, 0));
    int num = 1, b = 0, e = n-1;
    while(b < e) {        // use i uniformly is neat
        for(int i=b; i<e; i++) M[b][i] = num++;
        for(int i=b; i<e; i++) M[i][e] = num++;
        for(int i=e; i>b; i--) M[e][i] = num++;
        for(int i=e; i>b; i--) M[i][b] = num++;
        b++;
        e--;
    }
    if(b == e) M[b][e] = num; // gist, easy to forget
    return M;
}

// give a 2D m*n matrix, spread it spirally into a vector, recursive solution
void spread_spiral_matrix(vector<vector<int>> &M, vector<int> &res, int m, int n, int k) {
    if(m <= 0 || n <= 0) return;
    if(m == 1) {
        for(int i=0; i<n; i++) res.push_back(M[k][k+i]); // cannot forgot k
        return;
    }
    if(n == 1) {
        for(int j=0; j<m; j++) res.push_back(M[k+j][k]); 
        return;
    }
    for(int i=0; i<n-1; i++) res.push_back(M[k][k+i]);      // start from top left
    for(int i=0; i<m-1; i++) res.push_back(M[k+i][k+n-1]);  // start from top right
    for(int i=n-1; i>0; i--) res.push_back(M[k+m-1][k+i]);  // start from bottom right
    for(int i=m-1; i>0; i--) res.push_back(M[k+i][k]);      // start from bottom left
    spread_spiral_matrix(M, res, m-2, n-2, k+1); // gist
}
vector<int> spiralOrder(vector<vector<int> > &matrix) {
    vector<int> res;
    if(matrix.empty()) return res;
    spread_spiral_matrix(matrix, res, matrix.size(), matrix[0].size(), 0);
    return res;
}

以上是关于c_cpp [螺旋矩阵II]:给定整数n,生成以螺旋顺序填充1到n2的元素的方阵。例如,给定n =的主要内容,如果未能解决你的问题,请参考以下文章

59. 螺旋矩阵 II

Leetcode 59. 螺旋矩阵 II(Spiral Matrix II)

59. 螺旋矩阵 II

leetcode 59. 螺旋矩阵 II

leetcode 59. 螺旋矩阵 II

#yyds干货盘点# leetcode算法题:螺旋矩阵 II