Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 17, 2013 13:19
Show Gist options
  • Select an option

  • Save pdu/4971460 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4971460 to your computer and use it in GitHub Desktop.
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. http://leetcode.com/onlinejudge#question_54
#define INF 0x7fffffff
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
bool inBound(int x, int y, int n, int m) {
return x >= 0 && x < n && y >= 0 && y < m;
}
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ans;
int n = matrix.size();
if (n == 0)
return ans;
int m = matrix[0].size();
if (m == 0)
return ans;
int x = 0, y = 0;
int d = 0;
for (int i = 0; i < n * m; ++i) {
if (i != 0) {
while (true) {
int nx = x + dir[d][0], ny = y + dir[d][1];
if (inBound(nx, ny, n, m) && matrix[nx][ny] != INF) {
x = nx;
y = ny;
break;
}
d = (d + 1) % 4;
}
}
ans.push_back(matrix[x][y]);
matrix[x][y] = INF;
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment