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

Spiral Matrix

时间:2014-12-04 13:56:40      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

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) {
        vector <int> result;
        int row=matrix.size()-1;
        if (row==0) return matrix[0];
        else if (row==-1) return result;
        int col=matrix[0].size()-1;
        int layer=0;
        while(1){
            for (int i=layer;i<=col;++i)
                result.push_back(matrix[layer][i]);
            for (int i=layer+1;i<=row;++i)
                result.push_back(matrix[i][col]);
            for (int i=col-1;i>=layer&&layer!=row;--i)
                result.push_back(matrix[row][i]);
            for (int i=row-1;i>=layer+1&&layer!=col;--i)
                result.push_back(matrix[i][layer]);
            ++layer;
            --col;
            --row;
            if (layer>col||layer>row) break;
        }
        return result;
    }
};

 

Spiral Matrix

标签:style   blog   io   color   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/code-swan/p/4141242.html

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