1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: vector<vector<int>> generateMatrix(int n) { vector< vector<int> > matrix(n,vector<int>(n,0)); int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; int x = 0, y = 0, d = 1; int cnt=1; for (int i = 0; i < n * n; i ++ ) { matrix[x][y]=cnt; cnt++; int a = x + dx[d], b = y + dy[d]; if (a < 0 || a >= n || b < 0 || b >= n || matrix[a][b]) { d = (d + 1) % 4; a = x + dx[d], b = y + dy[d]; } x = a, y = b; } return matrix; } };
|