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

[LeetCode] Spiral Matrix

时间:2014-07-27 10:16:02      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example, Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        int m = matrix.size();//原矩阵m行n列
        vector<int> res;
        if(m==0)
            return res;
        int n = matrix[0].size();
        
        
        
        int rowStart=0,rowEnd=m-1,colStart=0,colEnd=n-1;
       
        int j=colStart,i=rowStart ;
        while(1)
        {
            
            for(j = colStart;j<=colEnd;j++)
            {
                res.push_back(matrix[i][j]);
            }
            j = j-1;
            if(res.size()==m*n)
                break;
            rowStart++;
            j = colEnd;

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

            }
            j = j+1;
            if(res.size()==m*n)
                break;
            rowEnd--;
            j=colStart;
            for(i = rowEnd;i>=rowStart;i--)
            {
                res.push_back(matrix[i][j]);
            }
            colStart++;
            i = rowStart;
        }//end while
    return res;
    }
};

 

[LeetCode] Spiral Matrix

标签:

原文地址:http://www.cnblogs.com/Xylophone/p/3870585.html

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