-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPrintMatrixInSpiralFormat.cpp
More file actions
88 lines (76 loc) · 1.59 KB
/
Copy pathPrintMatrixInSpiralFormat.cpp
File metadata and controls
88 lines (76 loc) · 1.59 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
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
/*
Print given matrix in spiral format
INPUT:
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
OUTPUT:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
*/
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c)
{
int outer;
if(r<c)
{
if(r%2==0)
outer=r/2;
else
outer=(r/2)+1;
}
else
{
if(c%2==0)
outer=c/2;
else
outer=(c/2)+1;
}
int x=y=0;
int i,j,k;
for( k=0; k<outer; k++)
{
i=k;
for( j=k;j<c;j++)
cout<<matrix[i][j]<<" ";
j=c;
for(i=c; i<r;i++)
cout<<matrix[i][j]<<" ";
i=r;
for(j=c;j>k;j--)
cout<<matrix[i][j]<<" ";
j=r;
for(i=r;i>k;i--)
cout<<matrix[i][j]<<" ";
}
}
};
int main() {
int t;
cin>>t;
while(t--)
{
int r,c;
cin>>r>>c;
vector<vector<int> > matrix(r);
for(int i=0; i<r; i++)
{
matrix[i].assign(c, 0);
for( int j=0; j<c; j++)
{
cin>>matrix[i][j];
}
}
Solution ob;
vector<int> result = ob.spirallyTraverse(matrix, r, c);
for (int i = 0; i < result.size(); ++i)
cout<<result[i]<<" ";
cout<<endl;
}
return 0;
}