0% found this document useful (0 votes)
129 views1 page

Spiral Matrix Traversal

This function takes in a 2D vector and returns a 1D vector containing the elements of the 2D vector in spiral order. It uses variables to track the top, bottom, left, and right bounds as well as a direction variable. It iterates through the 2D vector in a spiral pattern, adding the elements to the output vector by changing the bounds and direction after each iteration.

Uploaded by

Pavan Pulicherla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views1 page

Spiral Matrix Traversal

This function takes in a 2D vector and returns a 1D vector containing the elements of the 2D vector in spiral order. It uses variables to track the top, bottom, left, and right bounds as well as a direction variable. It iterates through the 2D vector in a spiral pattern, adding the elements to the output vector by changing the bounds and direction after each iteration.

Uploaded by

Pavan Pulicherla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

vector<int> Solution::spiralOrder(const vector<vector<int> > &A) {

int T,B,L,R,dir;
T=0;
B=A.size()-1;
L=0;
R=A[0].size()-1;
dir=0;
int i;
vector<int> ans;

while(T<=B && L<=R)


{
if(dir==0)
{
for(i=L;i<=R;i++)
ans.push_back(A[T][i]);
T++;
}
else if(dir==1)
{
for(i=T;i<=B;i++)
ans.push_back(A[i][R]);
R--;
}
else if(dir==2)
{
for(i=R;i>=L;i--)
ans.push_back(A[B][i]);
B--;
}
else if(dir==3)
{
for(i=B;i>=T;i--)
ans.push_back(A[i][L]);
L++;
}
dir=(dir+1)%4;
}
return ans;
}

You might also like