Created
July 14, 2020 09:03
-
-
Save JyotinderSingh/4a2d635140091beb0e98cadf2e7fb0e3 to your computer and use it in GitHub Desktop.
Spiral Matrix | Interview Question Explanation
This file contains hidden or 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
class Solution | |
{ | |
public: | |
vector<int> spiralOrder(vector<vector<int>> &matrix) | |
{ | |
vector<int> res; | |
if (!matrix.size()) | |
return res; | |
int rows = matrix.size(), cols = matrix[0].size(); | |
int total = rows * cols; | |
res.reserve(total); | |
int top = 0, down = rows - 1, left = 0, right = cols - 1; | |
while (left <= right && top <= down) | |
{ | |
// Traverse right | |
for (int i = left; i <= right && res.size() < total; ++i) | |
{ | |
res.push_back(matrix[top][i]); | |
} | |
top++; | |
// Traverse Down | |
for (int j = top; j <= down && res.size() < total; ++j) | |
{ | |
res.push_back(matrix[j][right]); | |
} | |
right--; | |
// Traverse left | |
for (int i = right; i >= left && res.size() < total; --i) | |
{ | |
res.push_back(matrix[down][i]); | |
} | |
down--; | |
// Traverse up | |
for (int j = down; j >= top && res.size() < total; --j) | |
{ | |
res.push_back(matrix[j][left]); | |
} | |
left++; | |
} | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment