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

打印螺旋矩阵

时间:2015-03-15 21:03:24      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

//代码来源:http://discuss.leetcode.com/questions/29/spiral-matrix
class Solution {      
public:      
    vector<int> spiralOrder(vector<vector<int> >& matrix) {      
        vector<int> result;      
        if (matrix.empty()) return result;      
        ssize_t beginX = 0, endX = matrix[0].size() - 1;      
        ssize_t beginY = 0, endY = matrix.size() - 1;      
  
        while (true) {      
            // From left to right      
            for (ssize_t i = beginX; i <= endX; ++i)      
                result.push_back(matrix[beginY][i]);      
            if (++beginY > endY) break;      
  
            // From top down      
            for (ssize_t i = beginY; i <= endY; ++i)      
                result.push_back(matrix[i][endX]);      
            if (beginX > --endX) break;      
  
            // From right to left      
            for (ssize_t i = endX; i >= beginX; --i)      
                result.push_back(matrix[endY][i]);      
            if (beginY > --endY) break;      
  
            // From bottom up      
            for (ssize_t i = endY; i >= beginY; --i)      
                result.push_back(matrix[i][beginX]);      
            if (++beginX > endX) break;      
        }      
        return result;      
    }      
}; 

 

打印螺旋矩阵

标签:

原文地址:http://www.cnblogs.com/david-wang/p/4340244.html

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