給定一個包含 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