Skip to content

Instantly share code, notes, and snippets.

@JyotinderSingh
Created July 14, 2020 09:03
Show Gist options
  • Save JyotinderSingh/4a2d635140091beb0e98cadf2e7fb0e3 to your computer and use it in GitHub Desktop.
Save JyotinderSingh/4a2d635140091beb0e98cadf2e7fb0e3 to your computer and use it in GitHub Desktop.
Spiral Matrix | Interview Question Explanation
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