Spirally traversing a matrix

PHOTO EMBED

Tue Nov 08 2022 03:34:36 GMT+0000 (Coordinated Universal Time)

Saved by @Ranjan_kumar #c++

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) 
    {
        
        int l=0;
        int ri=c-1;
        int u=0;
        int d=r-1;
        
        vector<int>v;
        while(l<=ri && u<=d)
        {
            for(int i=l;i<=ri;i++)
            {
                v.push_back(matrix[u][i]);
            }
            u++;
            
            for(int i=u;i<=d;i++)
            {
                v.push_back(matrix[i][ri]);
            }
            ri--;
            
            if(u<=d)
            {
                for(int i=ri;i>=l;i--)
                {
                    v.push_back(matrix[d][i]);
                }
                
                d--;
            }
            
            if(l<=ri)
            {
                for(int i=d;i>=u;i--)
                {
                    v.push_back(matrix[i][l]);
                }
                l++;
            }
        }
        return v;
    }
};
content_copyCOPY

https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article