Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Solution:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, 0));
int rLow = 0, rHigh = n-1;
int cLow = 0, cHigh = n-1;
int dir = 0, val = 1;
while (rLow <= rHigh && cLow <= cHigh) {
if (dir == 0) {
// right
for (int i=cLow; i<=cHigh; i++) {
ans[rLow][i] = val; val += 1;
}
rLow += 1;
} else if (dir == 1) {
// down
for (int i=rLow; i<=rHigh; i++) {
ans[i][cHigh] = val; val += 1;
}
cHigh -= 1;
} else if (dir == 2) {
// left
for (int i=cHigh; i>=cLow; i--) {
ans[rHigh][i] = val; val += 1;
}
rHigh -= 1;
} else {
// up
for (int i=rHigh; i>=rLow; i--) {
ans[i][cLow] = val; val += 1;
}
cLow += 1;
}
dir = (dir + 1) % 4;
}
return ans;
}