天天看点

螺旋矩阵-LintCode

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

样例:

给定如下矩阵:

[
    [ , ,  ],
    [ , ,  ],
    [ , ,  ]
]
           

应返回 [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[].empty())
            return res;
        int row = matrix.size();
        int col = matrix[].size();
        int i = , j = ;
        int iMin = , iMax = row - ;
        int jMin = , jMax = col - ;
        while (iMin<=iMax&&jMin<=jMax)
        {
            for (int i = jMin; i <= jMax; ++i)
                res.push_back(matrix[iMin][i]);
            for (int i = iMin + ; i <= iMax; ++i)
                res.push_back(matrix[i][jMax]);
            if (iMin < iMax)
            {
                for (int i = jMax - ; i >= jMin; --i)
                    res.push_back(matrix[iMax][i]);
            }
            if (jMin < jMax)
            {
                for (int i = iMax - ; i >= iMin + ; --i)
                    res.push_back(matrix[i][iMin]);
            }
            iMin++;
            jMin++;
            iMax--;
            jMax--;
        }
        return res;
    }
};
#endif