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

[LeetCode]54.Spiral Matrix

时间:2015-02-05 11:18:02      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:leetcode   经典面试题   数组   

【题目】

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].

【分析】

【代码】

    /**------------------------------------
    *   日期:2015-02-05
    *   作者:SJF0115
    *   题目: 54.Spiral Matrix
    *   网址:https://oj.leetcode.com/problems/spiral-matrix/
    *   结果:AC
    *   来源:LeetCode
    *   博客:
    ---------------------------------------**/
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int> > &matrix) {
            vector<int> result;
            if(matrix.empty()){
                return result;
            }//if
            int row = matrix.size();
            int col = matrix[0].size();
            int count = row * col;
            int index = 1;
            int beginX = 0,endX = row - 1;
            int beginY = 0,endY = col - 1;
            while(index <= count){
                // right
                for(int i = beginY;i <= endY;++i){
                    result.push_back(matrix[beginX][i]);
                    ++index;
                }//for
                ++beginX;
                if(beginX > endX){
                    break;
                }//if
                // down
                for(int i = beginX;i <= endX;++i){
                    result.push_back(matrix[i][endY]);
                    ++index;
                }//for
                --endY;
                if(endY < beginY){
                    break;
                }//if
                // left
                for(int i = endY;i >= beginY;--i){
                    result.push_back(matrix[endX][i]);
                    ++index;
                }//for
                --endX;
                if(endX < beginX){
                    break;
                }//if
                // up
                for(int i = endX;i >= beginX;--i){
                    result.push_back(matrix[i][beginY]);
                    ++index;
                }
                ++beginY;
                if(beginX > endY){
                    break;
                }//if
            }//while
            return result;
        }
    };

    int main(){
        Solution s;
        vector<vector<int> > matrix = {{1,2,3},{4,5,6},{7,8,9}};
        vector<int> result = s.spiralOrder(matrix);
        // 输出
        for(int i = 0;i < result.size();++i){
            cout<<result[i]<<"  ";
        }//for
        cout<<endl;
        return 0;
    }

技术分享

[LeetCode]54.Spiral Matrix

标签:leetcode   经典面试题   数组   

原文地址:http://blog.csdn.net/sunnyyoona/article/details/43525181

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