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:
You should return
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;
}
};
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;
}
};
相关文章推荐
- leetcode Spiral Matrix II
- LeetCode: Spiral Matrix II
- Leetcode Spiral Matrix
- [LeetCode 题解] Spiral Matrix
- [LeetCode] Spiral Matrix II
- LeetCode Spiral Matrix II
- Leetcode Spiral Matrix II
- [Leetcode] Spiral Matrix (Java)
- LeetCode-Spiral Matrix
- leetcode——54——Spiral Matrix
- 【leetcode】Spiral Matrix
- leetcode第一刷_Spiral Matrix
- LeetCode 54.Spiral Matrix (Medium)
- Leetcode算法学习日志-54 Spiral Matrix
- LeetCode Spiral Matrix
- LeetCode--Spiral Matrix
- leetcode — spiral-matrix-ii
- [LeetCode]Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode54 Spiral Matrix