-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralTraversal.cpp
43 lines (36 loc) · 1.01 KB
/
SpiralTraversal.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
#include<bits/stdc++.h>
using namespace std;
vector<int> spirallyTraverse(vector<vector<int> > matrix)
{
int r = matrix.size(), c = matrix[0].size();
int startCol = 0, startRow = 0, endCol = c - 1, endRow = r - 1;
vector<int> spiral;
int cnt = 0;
while(cnt < r*c) {
for(int i = startCol; i <= endCol && cnt < r*c; i++){
int ele = matrix[startCol][i];
spiral.push_back(ele);
cnt++;
}
startRow++;
for(int i = startRow; i<= endRow && cnt < r*c; i++){
int ele = matrix[i][endCol];
spiral.push_back(ele);
cnt++;
}
endCol--;
for(int i = endCol; i >= startCol && cnt < r*c; i--){
int ele = matrix[endRow][i];
spiral.push_back(ele);
cnt++;
}
endRow--;
for(int i = endRow; i >= startRow && cnt < r*c; i--){
int ele = matrix[i][startCol];
spiral.push_back(ele);
cnt++;
}
startCol++;
}
return spiral;
}