美文网首页
59. Spiral Matrix II

59. Spiral Matrix II

作者: Al73r | 来源:发表于2017-10-16 08:52 被阅读0次

题目

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;
    }
};

思考

相关文章

网友评论

      本文标题:59. Spiral Matrix II

      本文链接:https://www.haomeiwen.com/subject/zoohuxtx.html