Skip to content

Commit

Permalink
Merge pull request ZoranPandovski#3337 from akanksha0812/patch-2
Browse files Browse the repository at this point in the history
Spiral_Matrix.cpp
  • Loading branch information
ZoranPandovski authored Oct 14, 2022
2 parents 8f6151d + df9cccc commit 167b2e9
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions data_structures/matrix/cpp/Spiral_Matrix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int start = 0;
int i = start, j = start;

int rows = matrix.size();
int cols = matrix[0].size();
int n = rows*cols;
int count = 0;
vector<int>result;

while(count<n)
{
while(j<cols && count<n)
{
result.push_back(matrix[i][j]);
cout<<matrix[i][j]<<",";
j++;
count++;
}
i++;j--;

while(i<rows && count<n)
{
result.push_back(matrix[i][j]);
cout<<matrix[i][j]<<",";
i++;
count++;
}
j--;i--;

while(j>=start && count<n)
{
result.push_back(matrix[i][j]);
cout<<matrix[i][j]<<",";
j--;
count++;
}

i --;j++;

while(i>=(start+1) && count<n)
{
result.push_back(matrix[i][j]);
cout<<matrix[i][j]<<",";
i--;
count++;
}
rows-=1;cols-=1;
start++; i=j=start;

}
return result;

}
};

0 comments on commit 167b2e9

Please sign in to comment.