-
Notifications
You must be signed in to change notification settings - Fork 0
/
spiralPrint.cpp
88 lines (71 loc) · 1.77 KB
/
spiralPrint.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <bits/stdc++.h>
using namespace std;
void spiralOrder(vector<vector<int>> &matrix)
{
vector<int> ans;
int row = matrix.size();
int col = matrix[0].size();
int count = 0;
int total = row * col;
//index initialisation
int startingRow = 0;
int startingCol = 0;
int endingRow = row - 1;
int endingCol = col - 1;
while (count < total)
{
//print starting row
for (int index = startingCol; count < total && index <= endingCol; index++)
{
ans.push_back(matrix[startingRow][index]);
count++;
}
startingRow++;
//print ending column
for (int index = startingRow; count < total && index <= endingRow; index++)
{
ans.push_back(matrix[index][endingCol]);
count++;
}
endingCol--;
//print ending row
for (int index = endingCol; count < total && index >= startingCol; index--)
{
ans.push_back(matrix[endingRow][index]);
count++;
}
endingRow--;
//print starting column
for (int index = endingRow; count < total && index >= startingRow; index--)
{
ans.push_back(matrix[index][startingCol]);
count++;
}
startingCol++;
}
for(auto it:ans)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
int n; cin >> n;
int m; cin >> m;
vector<vector<int>> matrix;
for(int i=0;i<n;i++)
{
vector<int> colElements;
for(int j=0;j<m;j++)
{
int temp;
cin >> temp;
colElements.push_back(temp);
}
matrix.push_back(colElements);
}
spiralOrder(matrix);
return 0;
}
//T.C = O(n*m)