Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- #include <bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- 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
- int total=r*c;
- int top=0;
- int right=c-1;
- int bottom=r-1;
- int left=0;
- int count=0;
- vector<int> a;
- while(count<total)
- {
- int ind=top;
- for(int i=left;count<total && i<=right;i++)
- {
- a.push_back(matrix[top][i]);
- count++;
- }
- top++;
- for(int i=top;count<total && i<=bottom;i++)
- {
- a.push_back(matrix[i][right]);
- count++;
- }
- right--;
- for(int i=right;count<total && i>=left;i--)
- {
- a.push_back(matrix[bottom][i]);
- count++;
- }
- bottom--;
- for(int i=bottom;count<total && i>=top;i--)
- {
- a.push_back(matrix[i][left]);
- count++;
- }
- left++;
- }
- return a;
- }
- };
- //{ 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;
- }
- // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement