-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 9 May | 54. Spiral Matrix.cpp
- Loading branch information
1 parent
422867d
commit 6a2d82b
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |