首页 > 其他 > 详细

[LeetCode] Spiral Matrix II

时间:2014-07-27 10:21:02      阅读:300      评论: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<int> v(n,0);
        vector<vector<int>> res(n,v);
        int col = (n+1)/2-1;//结束点的行列号
        int row = n/2;
        int num = 1;
        int rowStart=0,rowEnd=n-1,colStart=0,colEnd=n-1;

        int j=colStart,i=rowStart ;
        while(1)
        {
            
            for(j = colStart;j<=colEnd;j++)
            {
                res[i][j] = num++;
            }
            j = j-1;
            if(i==row && j==col)
                break;
            rowStart++;
            j = colEnd;

            for(i=rowStart;i<=rowEnd;i++)
            {
                res[i][j] = num++;
            }
            colEnd--;
            i = rowEnd;
            for(j=colEnd;j>=colStart;j--)
            {
                res[i][j] = num++;

            }
            j = j+1;
            if(i==row && j==col)
                break;
            rowEnd--;
            j=colStart;
            for(i = rowEnd;i>=rowStart;i--)
            {
                res[i][j] = num++;
            }
            colStart++;
            i = rowStart;
        }//end while
    return res;
    }
};

 

[LeetCode] Spiral Matrix II

原文:http://www.cnblogs.com/Xylophone/p/3870570.html

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