-
Notifications
You must be signed in to change notification settings - Fork 2
/
printSpiralMatrix.cpp
52 lines (43 loc) · 1.42 KB
/
printSpiralMatrix.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
48
49
50
51
52
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
int row = matrix.size();
int col= matrix[0].size();
int count = 0;
int total = row*col;
int firstRow = 0;
int firstCol = 0;
int lastRow = row-1;
int lastCol = col-1;
while(count<total){
//print starting row
for(int index=firstCol; count<total && index<=lastCol ; index++){
ans.push_back(matrix[firstRow][index]);
count++;
}
firstRow++;
//print last column
for(int index=firstRow; count<total && index<=lastRow; index++){
ans.push_back(matrix[index][lastCol]);
count++;
}
lastCol--;
//print last row
for(int index = lastCol; count<total && index>=firstCol ;index--){
ans.push_back(matrix[lastRow][index]);
count++;
}
lastRow--;
//print first col
for(int index = lastRow; count<total && index>=firstRow ; index--){
ans.push_back(matrix[index][firstCol]);
count++;
}
firstCol++;
}
return ans;
}
};