Spiral traversal of matrix

PHOTO EMBED

Wed Jun 19 2024 03:05:02 GMT+0000 (Coordinated Universal Time)

Saved by @Xeno_SSY #c++

//{ 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) 
    {   
        vector<int> v;
        int startrow=0;
        int endrow=r-1;
        int startcol=0;
        int endcol=c-1;
        while(startrow<=endrow && startcol<=endcol){
            for(int i=startcol;i<=endcol && startrow<=endrow && startcol<=endcol;i++){
                v.push_back(matrix[startrow][i]);
            }
            startrow++;
            for(int i=startrow;i<=endrow && startrow<=endrow && startcol<=endcol;i++){
                v.push_back(matrix[i][endcol]);
            }
            endcol--;
            for(int i=endcol;i>=startcol && startrow<=endrow && startcol<=endcol;i--){
                v.push_back(matrix[endrow][i]);
            }
            endrow--;
            for(int i=endrow;i>=startrow && startrow<=endrow && startcol<=endcol;i--){
                v.push_back(matrix[i][startcol]);
            }
            startcol++;
        }
        return v;
        
    }
};

//{ 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
content_copyCOPY

mark the start and end rows and col and then add or subtract from each to get the desired pattern dont forget to check the start<=end criteria for each row/col traversal.