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

leetcode[54]Spiral Matrix

时间:2015-02-09 15:27:50      阅读:95      评论: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:
void  solve(vector<vector<int>> &matrix, vector<int> &res, int left, int right, int up, int down)
{
    if (up>down||left>right)
        return;
    if (up==down)
    {
        for (int j=left;j<=right;j++)
        {
           res.push_back(matrix[up][j]);
        }
        return;
    }
    if (left==right)
    {
        for (int i=up;i<=down;i++)
        {
            res.push_back(matrix[i][left]);
        }
        return;
    }
    for (int j=left;j<right;j++)
        res.push_back(matrix[up][j]);
    for (int i=up;i<down;i++)
        res.push_back(matrix[i][right]);
    for (int j=right;j>left;j--)
        res.push_back(matrix[down][j]);
    for(int i=down;i>up;i--)
        res.push_back(matrix[i][left]);
    solve(matrix, res, left+1, right-1, up+1, down-1);
}
vector<int> spiralOrder(vector<vector<int> > &matrix) 
{
    vector<int> res;
    if(matrix.empty())return res;
    solve(matrix,res,0,matrix[0].size()-1,0,matrix.size()-1);
    return res;
}
};

 

leetcode[54]Spiral Matrix

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4281543.html

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