码迷,mamicode.com
首页 > 其他好文 > 详细

Spiral Matrix II

时间:2014-11-20 23:21:17      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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 II

标签:style   blog   io   ar   color   os   sp   for   on   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!