|
| 1 | +// Time: O(m * n) |
| 2 | +// Space: O(1) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + vector<int> spiralOrder(vector<vector<int>>& matrix) { |
| 7 | + vector<int> result; |
| 8 | + if (matrix.empty()) { |
| 9 | + return result; |
| 10 | + } |
| 11 | + |
| 12 | + for (int left = 0, right = matrix[0].size() - 1, |
| 13 | + top = 0, bottom = matrix.size() - 1; |
| 14 | + left <= right && top <= bottom; |
| 15 | + ++left, --right, ++top, --bottom) { |
| 16 | + |
| 17 | + for (int j = left; j <= right; ++j) { |
| 18 | + result.emplace_back(matrix[top][j]); |
| 19 | + } |
| 20 | + for (int i = top + 1; i < bottom; ++i) { |
| 21 | + result.emplace_back(matrix[i][right]); |
| 22 | + } |
| 23 | + for (int j = right; top < bottom && j >= left; --j) { |
| 24 | + result.emplace_back(matrix[bottom][j]); |
| 25 | + } |
| 26 | + for (int i = bottom - 1; left < right && i > top; --i) { |
| 27 | + result.emplace_back(matrix[i][left]); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + return result; |
| 32 | + } |
| 33 | +}; |
| 34 | + |
| 35 | +// Time: O(m * n) |
| 36 | +// Space: O(1) |
| 37 | +class Solution2 { |
| 38 | +public: |
| 39 | + vector<int> spiralOrder(vector<vector<int>>& matrix) { |
| 40 | + const int m = matrix.size(); |
| 41 | + vector<int> ans; |
| 42 | + if (m == 0) { |
| 43 | + return ans; |
| 44 | + } |
| 45 | + |
| 46 | + const int n = matrix.front().size(); |
| 47 | + enum Action {RIGHT, DOWN, LEFT, UP}; |
| 48 | + Action action = RIGHT; |
| 49 | + for (int i = 0, j = 0, begini = 0, beginj = 0, endi = m, |
| 50 | + endj = n, cnt = 0, total = m * n; cnt < total; ++cnt) { |
| 51 | + |
| 52 | + ans.emplace_back(matrix[i][j]); |
| 53 | + |
| 54 | + switch (action) { |
| 55 | + case RIGHT: |
| 56 | + if (j + 1 < endj) { |
| 57 | + ++j; |
| 58 | + } else { |
| 59 | + action = DOWN, ++begini, ++i; |
| 60 | + } |
| 61 | + break; |
| 62 | + case DOWN: |
| 63 | + if (i + 1 < endi) { |
| 64 | + ++i; |
| 65 | + } else { |
| 66 | + action = LEFT, --endj, --j; |
| 67 | + } |
| 68 | + break; |
| 69 | + case LEFT: |
| 70 | + if (j - 1 >= beginj) { |
| 71 | + --j; |
| 72 | + } else { |
| 73 | + action = UP, --endi, --i; |
| 74 | + } |
| 75 | + break; |
| 76 | + case UP: |
| 77 | + if (i - 1 >= begini) { |
| 78 | + --i; |
| 79 | + } else { |
| 80 | + action = RIGHT, ++beginj, ++j; |
| 81 | + } |
| 82 | + break; |
| 83 | + default: |
| 84 | + break; |
| 85 | + } |
| 86 | + } |
| 87 | + return ans; |
| 88 | + } |
| 89 | +}; |
0 commit comments