LeetCode | 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 ]
]

思路:


http://blog.csdn.net/lanxu_yy/article/details/17528505完全类似。

代码:

class Solution {
public:
    vector<vector<int>> r;
    int cur;
    vector<vector<int>> generateMatrix(int n) {
        if(n==0)
        {
            return *(new vector<vector<int>>());
        }

        r.resize(n);
        for(int i=0;i<n;i++)
        {
            r[i].resize(n);
        }
        int x1=0;
        int y1=0;
        int y2=r.size()-1;
        int x2=r[0].size()-1;
        
        cur=1;
        getOutside(true, x1, y1, x2, y2, r);
        return r;
    }
    
    void getOutside(bool upside, int x1, int y1, int x2, int y2,vector<vector<int> > &matrix)
    {
        if(x1 == x2 && y1 == y2)
        {
            matrix[y1][x1] = cur++;
        }
        else
        {
            if(upside)
            {
                for(int i=x1;i<=x2;i++)
                {
                    matrix[y1][i] = cur++;
                }
                if(y2>y1)
                {
                    for(int i=y1+1;i<=y2;i++)
                    {
                        matrix[i][x2] = cur++;
                    }
                }
                int x3 = x2-1;
                int y3 = y2;
                int x4 = x1;
                int y4 = y1+1;
                if(x3>=x4 && y3>=y4)
                {
                    getOutside(!upside, x3, y3, x4, y4,matrix);
                }
            }
            else
            {
                for(int i=x1;i>=x2;i--)
                {
                    matrix[y1][i] = cur++;
                }
                if(y1>y2)
                {
                    for(int i=y1-1;i>=y2;i--)
                    {
                        matrix[i][x2] = cur++;
                    }
                }
                int x3 = x2+1;
                int y3 = y2;
                int x4 = x1;
                int y4 = y1-1;
                if(x3<=x4 && y3<=y4)
                {
                    getOutside(!upside, x3, y3, x4, y4,matrix);
                }
            }
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17529025
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞