Advertisement
jayati

Spirally traversing a matrix

Sep 17th, 2023
717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution
  7. {  
  8.     public:
  9.     //Function to return a list of integers denoting spiral traversal of matrix.
  10.     vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c)
  11.     {
  12.         // code here
  13.         int total=r*c;
  14.         int top=0;
  15.         int right=c-1;
  16.         int bottom=r-1;
  17.         int left=0;
  18.         int count=0;
  19.         vector<int> a;
  20.         while(count<total)
  21.         {
  22.             int ind=top;
  23.             for(int i=left;count<total && i<=right;i++)
  24.             {
  25.                 a.push_back(matrix[top][i]);
  26.                 count++;
  27.                
  28.             }
  29.            
  30.             top++;
  31.             for(int i=top;count<total && i<=bottom;i++)
  32.             {
  33.                 a.push_back(matrix[i][right]);
  34.                 count++;
  35.                
  36.             }
  37.             right--;
  38.             for(int i=right;count<total && i>=left;i--)
  39.             {
  40.                 a.push_back(matrix[bottom][i]);
  41.                 count++;
  42.             }
  43.             bottom--;
  44.             for(int i=bottom;count<total && i>=top;i--)
  45.             {
  46.                 a.push_back(matrix[i][left]);
  47.                 count++;
  48.             }
  49.             left++;
  50.            
  51.            
  52.         }
  53.         return a;
  54.     }
  55. };
  56.  
  57. //{ Driver Code Starts.
  58. int main() {
  59.     int t;
  60.     cin>>t;
  61.    
  62.     while(t--)
  63.     {
  64.         int r,c;
  65.         cin>>r>>c;
  66.         vector<vector<int> > matrix(r);
  67.  
  68.         for(int i=0; i<r; i++)
  69.         {
  70.             matrix[i].assign(c, 0);
  71.             for( int j=0; j<c; j++)
  72.             {
  73.                 cin>>matrix[i][j];
  74.             }
  75.         }
  76.  
  77.         Solution ob;
  78.         vector<int> result = ob.spirallyTraverse(matrix, r, c);
  79.         for (int i = 0; i < result.size(); ++i)
  80.                 cout<<result[i]<<" ";
  81.         cout<<endl;
  82.     }
  83.     return 0;
  84. }
  85. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement