给定一个包含 m x n 个要素的矩阵,(m 行, n 列),按照螺旋顺序,返回该矩阵中的所有要素。
样例
样例 1:
输入:[[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]
输出: [1,2,3,6,9,8,7,4,5]
样例 2
输入:[[ 6,4,1 ], [ 7,8,9 ]]
输出: [6,4,1,9,8,7]
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.size()==0) return res;
int n=matrix.size();
int m=matrix[0].size();
int count=0;
while(count*2<n&&count*2<m)
{
for (int i = count; i < m-count; i++) {
/* code */
res.push_back(matrix[count][i]);
}
for (int i = count+1; i < n-count; i++) {
/* code */
res.push_back(matrix[i][m-count-1]);
}
if (count * 2 == m - 1 || count * 2 == n - 1)
{
break;
}
for (int i = m-count-2; i >= count ; i--) {
/* code */
res.push_back(matrix[n-count-1][i]);
}
for (int i = n-count-2; i >= count+1; i--) {
/* code */
res.push_back(matrix[i][count]);
}
count++;
}
return res;
}
};