首页 > 其他 > 详细

Spiral Matrix II

时间:2014-03-12 16:26:36      阅读:242      评论:0      收藏: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 ]
]

写一个回旋的矩阵
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> >re;
        for(int i = 0 ;i < n; i++)
        {
            vector <int> temp(n,0);
            re.push_back(temp);
        }
        int direction =0;   //0 right ,1 down ,2 left, 3 up
        int length = n;
        int x = 0;
        int y = 0;
        int step = 0;
        for(int i = 1 ; i <= n*n ; i++)
        {
            re[x][y] = i;
            step++;
            if(step == length)  //should turn
            {
                direction = (direction + 1)%4;
                if(direction == 0)
                {
                    y = y+1;
                    step = 0;
                }
                else if(direction == 1)
                {
                    x = x+1;
                    length--;
                    step = 0;
                }
                else if(direction == 2)
                {
                    y = y-1;
                    step = 0;
                }
                else
                {
                    x = x-1;
                    length--;
                    step = 0;
                }
            }
            else
            {
                if(direction == 0) y = y+1;
                else if(direction == 1)x = x+1;
                else if(direction == 2)y = y-1;
                else x = x-1;
            }
            
        }
        return re;
    }
};

  

Spiral Matrix II,布布扣,bubuko.com

Spiral Matrix II

原文:http://www.cnblogs.com/pengyu2003/p/3595609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!