Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution { public: vector<vector<int> > generateMatrix(int n) { if (n == 0) return vector<vector<int> >(); static const int dy[] = {0,1,0,-1}; // right, down, left, up static const int dx[] = {1,0,-1,0}; vector<vector<int> > res; res.resize(n); for (int i = 0; i < n; ++i) res[i].resize(n,0); int cur = 1; for (int i = 0; i < n; ++i) res[0][i] = cur++; for (int i = 1; i < n; ++i) res[i][n-1] = cur++; for (int i = n-2; i >= 0; --i) res[n-1][i] = cur++; int y = n-1, x = 0, dir = 3; int t = n*n; while (cur <= t) { if (res[y+dy[dir%4]][x+dx[dir%4]] != 0) { dir++; continue; } y += dy[dir%4]; x += dx[dir%4]; res[y][x] = cur++; } return res; } };