Skip to content

Instantly share code, notes, and snippets.

@junjiah
Created January 1, 2014 09:02
Show Gist options
  • Save junjiah/8206324 to your computer and use it in GitHub Desktop.
Save junjiah/8206324 to your computer and use it in GitHub Desktop.
solved 'Spiral Matrix II ' on LeetCode http://oj.leetcode.com/problems/spiral-matrix-ii/
class Solution {
public:
enum Direction {RIGHT, LEFT, DOWN, UP};
vector<vector<int> > generateMatrix(int n) {
// init
i = 0; j = 0; matrix_size = n;
result.clear();
vector<int> v;
Direction d = RIGHT;
for (int i=0; i<n; ++i) v.push_back(0);
for (int i=0; i<n; ++i) result.push_back(v);
for (int ii=0; ii<n*n; ++ii)
d = mark(d, ii+1);
return result;
}
private:
int i, j, matrix_size;
vector<vector<int> > result;
Direction mark(const Direction d, int m) {
result[i][j] = m;
Direction next_d = d;
switch (d) {
case RIGHT:
if (j == matrix_size-1 ||
result[i][j+1] != 0) {
next_d = DOWN;
++i;
}
else
++j;
break;
case DOWN:
if (i == matrix_size-1 ||
result[i+1][j] != 0) {
next_d = LEFT;
--j;
}
else
++i;
break;
case LEFT:
if (j == 0 || result[i][j-1] != 0) {
next_d = UP;
--i;
}
else
--j;
break;
case UP:
if (result[i-1][j] != 0) {
next_d = RIGHT;
++j;
}
else
--i;
}
return next_d;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment