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