1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution { public: vector<int> spiralOrder(vector<vector<int>> &matrix) { int m = matrix.size(); int n = matrix[0].size(); vector<int> res(m * n);
int i = 0, j = 0, index = 0, dir = 0; int leftBound = 0, rightBound = n - 1, upBound = 0, downBound = m - 1; vector<vector<int>> direction = { {0, 1}, {1, 0}, {0, -1}, {-1, 0}}; while (leftBound < rightBound && upBound < downBound) { res[index++] = matrix[i][j]; if (dir == 0 && j == rightBound) { ++upBound; dir = (dir + 1) % 4; } else if (dir == 1 && i == downBound) { --rightBound; dir = (dir + 1) % 4; } else if (dir == 2 && j == leftBound) { --downBound; dir = (dir + 1) % 4; } else if (dir == 3 && i == upBound) { ++leftBound; dir = (dir + 1) % 4; }
i += direction[dir][0]; j += direction[dir][1]; } ++dir;
return res; } };
|