Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions Spiral Matrix/Spiral Matrix Solution
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
lass Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int row = matrix.size();
int col = matrix[0].size();

vector<int> ans;

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

int starting_row = 0;
int starting_col = 0;
int ending_row = row-1;
int ending_col = col-1;

while(count<total){
for(int index = starting_col; count<total && index<=ending_col; index++){
ans.push_back(matrix[starting_row][index]);
count++;
}
starting_row++;

for(int index = starting_row; count<total && index<=ending_row; index++){
ans.push_back(matrix[index][ending_col]);
count++;
}
ending_col--;

for(int index = ending_col; count<total && index>=starting_col; index--){
ans.push_back(matrix[ending_row][index]);
count++;
}
ending_row--;

for(int index = ending_row; count<total && index>=starting_row; index--){
ans.push_back(matrix[index][starting_col]);
count++;
}
starting_col++;
}
return ans;
}
};