Skip to content

Instantly share code, notes, and snippets.

@geraint0923
Created November 10, 2014 03:41
Show Gist options
  • Select an option

  • Save geraint0923/e075ce4b42df451cd4df to your computer and use it in GitHub Desktop.

Select an option

Save geraint0923/e075ce4b42df451cd4df to your computer and use it in GitHub Desktop.
Spiral Matrix II
class Solution {
public:
void fill(vector<vector<int> > &vec, int dir, int idx, int start, int end, int &next) {
switch(dir) {
case 0: // left -> right
for(int i = start; i <= end; i++) {
vec[idx][i] = next;
next++;
}
break;
case 1: // up -> bottom
for(int i = start; i <= end; i++) {
vec[i][idx] = next;
next++;
}
break;
case 2: // right -> left
for(int i = start; i >= end; i--) {
vec[idx][i] = next;
next++;
}
break;
case 3: // bottom -> up
for(int i = start; i >= end; i--) {
vec[i][idx] = next;
next++;
}
break;
}
}
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > vec;
for(int i = 0; i < n; i++) {
vector<int> r;
for(int j = 0; j < n; j++) {
r.push_back(0);
}
vec.push_back(r);
}
int gap = n, dir = 0, next = 1;
int l = 0, r = n-1, u = 0, b = n-1;
while(gap) {
switch(dir) {
case 0:
fill(vec, dir, u, l, r, next);
u++;
gap = b - u + 1;
dir = 1;
break;
case 1:
fill(vec, dir, r, u, b, next);
r--;
gap = r - l + 1;
dir = 2;
break;
case 2:
fill(vec, dir, b, r, l, next);
b--;
gap = b - u + 1;
dir = 3;
break;
case 3:
fill(vec, dir, l, b, u, next);
l++;
gap = r - l + 1;
dir = 0;
break;
}
}
return vec;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment