Skip to content

Commit

Permalink
Create 9 May | 54. Spiral Matrix.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
SumitPareek2401 authored May 9, 2023
1 parent 422867d commit 6a2d82b
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions 9 May | 54. Spiral Matrix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {

vector<int>ans;

int row = matrix.size();
int col = matrix[0].size();

int count = 0;
int total = row*col;

//index initialization
int startingRow = 0;
int startingCol = 0;
int endingRow = row-1;
int endingCol = col-1;

while(count < total){

//printing starting row
for(int index = startingCol; count < total && index <=endingCol; index++){
ans.push_back(matrix[startingRow][index]);
count++;
}
startingRow++;

//printing ending column
for(int index = startingRow; count < total && index <=endingRow; index++){
ans.push_back(matrix[index][endingCol]);
count++;
}
endingCol--;

//printing ending row
for(int index = endingCol; count < total && index >= startingCol; index--){
ans.push_back(matrix[endingRow][index]);
count++;
}
endingRow--;

//printing starting column
for(int index = endingRow; count < total && index >= startingRow; index--){
ans.push_back(matrix[index][startingCol]);
count++;
}
startingCol++;
}
return ans;
}
};

0 comments on commit 6a2d82b

Please sign in to comment.