leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0054.cpp (1017B)


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