Leetcode 59 Spiral Matrix II

2018-01-12 15:04:14 浏览数 (1)

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,

Given n = 3,

You should return the following matrix:

代码语言:javascript复制
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

方阵蛇形填数

和上一道蛇形取数差不多。

https://cloud.tencent.com/developer/article/1019259

代码语言:javascript复制
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<int> row(n,0);
        vector<vector<int>> result(n,row);
        int rows=n,cols=n,cnt=0;
        for(int x=0,y=0;x<rows && y<cols;x  ,y  )
        {
            for(int i=y;i<cols;i  ) result[x][i]=  cnt;
            for(int i=x 1;i<rows;i  ) result[i][cols-1]=  cnt;
            for(int i=cols-2;i>=y;i--) result[rows-1][i]=  cnt;
            for(int i=rows-2;i>x;i--) result[i][y]=  cnt;
            rows--;
            cols--;
        }
        return result;
    }
};

0 人点赞