首页 > 其他 > 详细

Spiral Matrix II

时间:2014-03-08 16:06:26      阅读:480      评论: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 ]
]

按照顺时针分别处理 “上,右,下,左”四条边,每处理完一条相应更新firstrow, lastcol, lastrow, firstcol四个变量,这样的话处理四条边的循环就被抽象为处理给定起始点的一条边。

因为是一个n*n的方阵,所以边界条件只在循环处判断firstrow <= lastrow就行了,如果是n*m则需要在每次更新firstrow和firstcol之后判断是否应该退出。

-------------------
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (n < 1) return vector<vector<int>>();
        vector<vector<int>> ret(n, vector<int>(n, 0));
        int cval = 1;
        int firstRow = 0, lastRow = n - 1;
        int firstCol = 0, lastCol = n - 1;
        while (firstRow <= lastRow) {
            for (int j = firstCol; j <= lastCol; j++) {
                ret[firstRow][j] = cval++;
            }
            
            firstRow++;
            for (int j = firstRow; j <= lastRow; j++) {
                ret[j][lastCol] = cval++;
            }
            
            lastCol--;
            for (int j = lastCol; j >= firstCol; j--) {
                ret[lastRow][j] = cval++;
            }
            
            lastRow--;
            for (int j = lastRow; j >= firstRow; j--) {
                ret[j][firstCol] = cval++;
            }
            firstCol++;
        }
        
        return ret;
    }
    
    
};

Spiral Matrix II,布布扣,bubuko.com

Spiral Matrix II

原文:http://blog.csdn.net/icomputational/article/details/20771135

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