//{ 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
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter