-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathSpiral_Matrix.cpp
47 lines (39 loc) · 1.3 KB
/
Spiral_Matrix.cpp
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
46
47
//Spiral Matrix
// Leetcode link: https://leetcode.com/problems/spiral-matrix/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> v;
int row = matrix.size();
int col = matrix[0].size();
int total = row*col;
int count = 0;
int firstRow =0;
int firstCol =0;
int lastRow =row-1;
int lastCol =col-1;
while(count < total){
for(int i = firstCol; count < total && i <= lastCol; i++){
v.push_back(matrix[firstRow][i]);
count++;
}
firstRow++;
for(int i = firstRow; count < total && i <= lastRow; i++){
v.push_back(matrix[i][lastCol]);
count++;
}
lastCol--;
for(int i = lastCol; count < total && i >= firstCol; i--){
v.push_back(matrix[lastRow][i]);
count++;
}
lastRow--;
for(int i = lastRow; count < total && i >= firstRow; i--){
v.push_back(matrix[i][firstCol]);
count++;
}
firstCol++;
}
return v;
}
};