Leetcde 59. Spiral Matrix II

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

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

题目链接:https://leetcode.com/problems/spiral-matrix-ii/

思路:在我之前的Leetcode 54. Spiral Matrix一步一个坑的基础上,改一下就好了,不要太简单,看来坑踩了还是有好处的

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
       vector<vector<int>> res;
        for(int i=0;i<n;i++)
        {
            vector<int> tmp;
            for(int j=0;j<n;j++)
            {
                tmp.push_back(0);
            }
            res.push_back(tmp);
        }
        int c=1;
        for(int i=0;i<=n/2;i++)
        {
            for(int j=i;j<n-i;j++)
            {
                if(res[i][j]==0)
                {
                    res[i][j]=c;
                    c++;
                }
                
            }
            for(int j=i+1;j<n-i;j++)
            {
                if(res[j][n-1-i]==0)
                {
                   res[j][n-1-i]=c;
                    c++;
                } 
            }
            for(int j=n-i-2;j>=i;j--)
            {
                if(res[n-1-i][j]==0)
                {
                    res[n-1-i][j]=c;
                    c++;
                }
                
            }
            for(int j=i+2;j<n-i;j++)
            {
                if(res[n-j][i]==0)
                {
                    res[n-j][i]=c;
                    c++;
                }   
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/86535765