-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiral_matrix.cpp
More file actions
45 lines (37 loc) · 1.13 KB
/
spiral_matrix.cpp
File metadata and controls
45 lines (37 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 54. Spiral Matrix: https://leetcode.com/problems/spiral-matrix/description/
// medium, matrix manipulation
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
int top = 0, bottom = matrix.size(), left = 0, right = matrix[0].size();
// base case
if(matrix.empty()) return ans;
while(left < right && top < bottom)
{
for(int i = left; i < right; i++){
ans.push_back(matrix[top][i]);
}
top++;
for(int i = top; i < bottom; i++){
ans.push_back(matrix[i][right - 1]);
}
right--;
if(top < bottom){
for(int i = right - 1; i >= left; i--){
ans.push_back(matrix[bottom - 1][i]);
}
bottom--;
}
if(left < right){
for(int i = bottom - 1; i >= top; i--){
ans.push_back(matrix[i][left]);
}
left++;
}
}
return ans;
}
};
// TC : O(m * n)
// SC : ans O(n)