螺旋矩阵-LintCode

来源:互联网 发布:腾讯微信用户数据报告 编辑:程序博客网 时间:2024/05/17 22:01

给定一个包含 m x n 个要素的矩阵,(m 行, n 列),按照螺旋顺序,返回该矩阵中的所有要素。
样例:
给定如下矩阵:

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

应返回 [1,2,3,6,9,8,7,4,5]。

#ifndef C374_H#define C374_H#include<iostream>#include<vector>using namespace std;class Solution {public:    /*    * @param matrix: a matrix of m x n elements    * @return: an integer list    */    vector<int> spiralOrder(vector<vector<int>> &matrix) {        // write your code here        vector<int> res;        if (matrix.empty()||matrix[0].empty())            return res;        int row = matrix.size();        int col = matrix[0].size();        int i = 0, j = 0;        int iMin = 0, iMax = row - 1;        int jMin = 0, jMax = col - 1;        while (iMin<=iMax&&jMin<=jMax)        {            for (int i = jMin; i <= jMax; ++i)                res.push_back(matrix[iMin][i]);            for (int i = iMin + 1; i <= iMax; ++i)                res.push_back(matrix[i][jMax]);            if (iMin < iMax)            {                for (int i = jMax - 1; i >= jMin; --i)                    res.push_back(matrix[iMax][i]);            }            if (jMin < jMax)            {                for (int i = iMax - 1; i >= iMin + 1; --i)                    res.push_back(matrix[i][iMin]);            }            iMin++;            jMin++;            iMax--;            jMax--;        }        return res;    }};#endif
原创粉丝点击