59. Spiral Matrix II

题目

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:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

分析

思路基本可54题一致,权当是把这道题练熟悉一点吧。

实现

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        if(n==0) return {};
        vector<vector<int>> ans(n, vector<int>(n, 0));
        int layers=(n-1)/2, x=0, y=0, i=1;
        for(int l=0; l<=layers; l++){
            while(y<=n-l-1){
                ans[x][y] = i;
                y++; i++;
            }
            y--; x++;
            while(x<=n-l-1){
                ans[x][y] = i;
                x++; i++;
            }
            x--; y--;
            while(y>=l){
                ans[x][y] = i;
                y--; i++;
            }
            y++; x--;
            while(x>=l+1){
                ans[x][y] = i;
                x--; i++;
            }
            x++; y++;
        }
        return ans;
    }
};

思考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容