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

C++实现代码:(注意奇数和偶数的不同)

#include<iostream>
#include<vector>
using namespace std;

class Solution
{
public:
    vector<vector<int> > generateMatrix(int n)
    {
        if(n==0)
            return vector<vector<int> >();
        vector<vector<int> > vec(n,vector<int>(n));
        int i,j;
        int count=1;
        i=0,j=0;
        while(((n%2)&&(count<n*n))||((n%2==0)&&(count<=n*n)))
        {
            for(; j<n-i-1; j++)
            {
                vec[i][j]=count;
                count++;
            }
            for(; i<j; i++)
            {
                vec[i][j]=count;
                count++;
            }
            for(; j>n-i-1; j--)
            {
                vec[i][j]=count;
                count++;
            }
            for(; i>j; i--)
            {
                vec[i][j]=count;
                count++;
            }
            i++;
            j++;
        }
        if(n%2)
            vec[i][j]=count;
        return vec;
    }
};

int main()
{
    Solution s;
    vector<vector<int> > result=s.generateMatrix(4);
    for(auto a:result)
    {
        for(auto v:a)
            cout<<v<<" ";
        cout<<endl;
    }
    cout<<endl;
}

 改进的方法,与Spiral Matrix类似的方法:

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        if(n<=0)
            return vector<vector<int> >();
        int count=1;
        int xmin=0;
        int xmax=n-1;
        int ymin=0;
        int ymax=n-1;
        vector<vector<int> > res(n,vector<int>(n));
        int i=0;
        int j=0;
        res[i][j]=count++;
        while(count<=n*n)
        {
            while(j<xmax) res[i][++j]=count++;
            if(++ymin>ymax)
                break;
            while(i<ymax) res[++i][j]=count++;
            if(--xmax<xmin)
                break;
            while(j>xmin) res[i][--j]=count++;
            if(--ymax<ymin)
                break;
            while(i>ymin) res[--i][j]=count++;
            if(++xmin>xmax)
                break;
        }
        return res;
    }
};

 

原文地址:https://www.cnblogs.com/wuchanming/p/4111628.html