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;
}
};
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