您的位置:首页 > 其它

LeetCode (Spiral Matrix)

2017-05-06 14:22 274 查看
Problem:

Given a matrix of m x n elements (m rows, 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]
.
Solution:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
if(matrix.empty()) return ans;
int m = matrix.size();
int n = matrix[0].size();
if(m == 1) return matrix[0];
for(int i = 0; i < n; i++)
ans.push_back(matrix[0][i]);
vector<vector<int>> m1;
for(int j = n - 1; j >= 0; j--){
vector<int> p;
for(int i = 1; i < m; i++)
p.push_back(matrix[i][j]);
m1.push_back(p);
}
vector<int> temp = spiralOrder(m1);
ans.insert(ans.end(), temp.begin(), temp.end());
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: