首页 > 其他 > 详细

leetcode笔记:Spiral Matrix

时间:2015-12-13 15:36:29      阅读:128      评论:0      收藏:0      [点我收藏+]

一. 题目描述

Given a matrix ofmn elements (mrows, 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].

二. 题目分析

题意:给定一个m*n的矩阵,从外围一层一层的打印出矩阵中的元素内容。解题的方法有多种,以下采用的方法是,使用四个数字分别记录上下左右四个边界的位置(beginX,endX,beginY,endY),不断循环以收窄这些边界,最终当两个边界重叠时,结束循环。

同时,当循环完成后,即得到所求数组。

三. 示例代码

class Solution 
{
public:
    vector<int> spiralOrder(vector<vector<int> >& matrix) {
        vector<int> result;
        if (matrix.empty()) return result;
        int beginX = 0, endX = matrix[0].size() - 1;
        int beginY = 0, endY = matrix.size() - 1;
        while (1) {
            // 从左到右
            for (int i = beginX; i <= endX; ++i)
                result.push_back(matrix[beginY][i]);
            if (++beginY > endY) break;
            // 从上到下
            for (int i = beginY; i <= endY; ++i)
                result.push_back(matrix[i][endX]);
            if (beginX > --endX) break;
            // 从右到左
            for (int i = endX; i >= beginX; --i)
                result.push_back(matrix[endY][i]);
            if (beginY > --endY) break;
            // 从下到上
            for (int i = endY; i >= beginY; --i)
                result.push_back(matrix[i][beginX]);
            if (++beginX > endX) break;
        }
        return result;
    }
};

leetcode笔记:Spiral Matrix

原文:http://blog.csdn.net/liyuefeilong/article/details/50278367

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!