-
Notifications
You must be signed in to change notification settings - Fork 387
Expand file tree
/
Copy pathtraversematrixspirally.cpp
More file actions
71 lines (60 loc) · 1.67 KB
/
traversematrixspirally.cpp
File metadata and controls
71 lines (60 loc) · 1.67 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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
//Function to return a list of integers denoting spiral traversal of matrix.
vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c)
{
// code here
vector <int > vec;
int top=0 , down = r-1 , left =0, right=c-1;
int dir=0;
while(top<=down && left<=right)
{
if(dir==0) {for(int i=left;i<=right;i++) {
vec.push_back(matrix[top][i]);}
top+=1;
}
else if(dir==1) {for(int i=top;i<=down;i++) {
vec.push_back(matrix[i][right]);}
right-=1;
}
else if(dir==2) {for(int i=right;i>=left;i--) {
vec.push_back(matrix[down][i]);}
down-=1;
}
else if(dir==3) {for(int i=down;i>=top;i--) {
vec.push_back(matrix[i][left]);}
left+=1;
}
dir=(dir+1)%4;
}
return vec;
}
};
// { Driver Code Starts.
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;
}