Skip to content

Instantly share code, notes, and snippets.

@valep27
Last active August 29, 2015 14:28
Show Gist options
  • Save valep27/9b49dcd12e32f89b20ad to your computer and use it in GitHub Desktop.
Save valep27/9b49dcd12e32f89b20ad to your computer and use it in GitHub Desktop.
Matrix traversal in spiral order (left to right)
vector<int> spiralOrder(const vector<vector<int>> &A) {
vector<int> result;
int i = 0, j = 0;
int startI = 0, startJ = 1;
int rows = A.size();
int cols = A[0].size();
int total = rows*cols;
while (result.size() < total) {
// over a row
for (; i < cols; i++) {
if (result.size() == total)
return result;
result.push_back(A[j][i]);
}
// over a column
for (i--, j++; j < rows; j++) {
if (result.size() == total)
return result;
result.push_back(A[j][i]);
}
// go back in a row
for (j--, i--; i >= startI; i--) {
if (result.size() == total)
return result;
result.push_back(A[j][i]);
}
// go back in a column (avoid last item)
for (i++, j--; j >= startJ; j--) {
if (result.size() == total)
return result;
result.push_back(A[j][i]);
}
// restrict to inner rectangle and repeat
i++;j++;
startI++;startJ++;
cols--; rows--;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment