forked from ZoranPandovski/al-go-rithms
-
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.
Merge pull request ZoranPandovski#3337 from akanksha0812/patch-2
Spiral_Matrix.cpp
- Loading branch information
Showing
1 changed file
with
57 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,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; | ||
|
||
} | ||
}; |