Skip to content

Instantly share code, notes, and snippets.

@cruxrebels
Last active July 20, 2021 08:35
Show Gist options
  • Save cruxrebels/465528c348b99b92e4cee1b002dfae45 to your computer and use it in GitHub Desktop.
Save cruxrebels/465528c348b99b92e4cee1b002dfae45 to your computer and use it in GitHub Desktop.
Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order. Example: Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1, 2, 3, 6, 9, 8, 7, 4, 5]. Tags: InterviewBit - Arrays topic (https://www.interviewbit.com/problems/spiral-order-matrix-i/).
vector<int> Solution::spiralOrder(const vector<vector<int> > &A) {
vector<int> result;
// DO STUFF HERE AND POPULATE result
auto rows = A.size
if (rows == 0)
return vector<int> ();
auto columns = A[0].size();
int T, B, L, R;
T = 0, B = rows - 1, L = 0, R = columns - 1;
int dir = 0;
while(T<=B && L<=R)
{
switch(dir)
{
case 0:
for(auto i=L; i<=R; ++i)
{
result.emplace_back(A[T][i]);
}
T++;
break;
case 1:
for(auto j=T; j<=B; ++j)
{
result.emplace_back(A[j][R]);
}
R--;
break;
case 2:
for(auto k=R; k>=L; --k)
{
result.emplace_back(A[B][k]);
}
B--;
break;
case 3:
for(auto l=B; l>=T; --l)
{
result.emplace_back(A[l][L]);
}
L++;
break;
default:
std::cout<<"Inside default\n";
break;
}
dir = (dir + 1)%4;
}
return result;
}
@DynamiteC
Copy link

you might be getting error, make "A.size" on line 4 to "A.size()" for cpp.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment