0054.cpp (1017B)
1 class Solution { 2 pair<int, int> offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 3 int limit_offset[4] = {1, -1, -1, 1}; 4 int limit[4] = {0, 0, 0, 0}; 5 6 int &m = limit[2], &n = limit[1]; 7 8 bool valid(int i, int j) { return i >= limit[0] && i <= m && j >= limit[3] && j <= n; } 9 10 public: 11 vector<int> spiralOrder(vector<vector<int>> &matrix) { 12 vector<int> res; 13 int direction = 0; 14 int cnt = 0; 15 int size; 16 int i = 0, j = 0; 17 18 m = matrix.size() - 1; 19 n = matrix[0].size() - 1; 20 size = (m + 1) * (n + 1); 21 22 while (true) { 23 res.push_back(matrix[i][j]); 24 if (++cnt == size) break; 25 26 if (!valid(i + offset[direction].first, j + offset[direction].second)) { 27 limit[direction] += limit_offset[direction]; 28 direction = (direction + 1) % 4; 29 } 30 31 i += offset[direction].first; 32 j += offset[direction].second; 33 } 34 35 return res; 36 } 37 };