leetcode

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

2326.cpp (1071B)


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<vector<int>> spiralMatrix(int dm, int dn, ListNode *head) {
11 vector<vector<int>> res(dm, vector<int>(dn, -1));
12 int direction = 0;
13 int cnt = 0;
14 int size;
15 int i = 0, j = 0;
17 m = dm - 1;
18 n = dn - 1;
19 size = (m + 1) * (n + 1);
21 while (true) {
22 res[i][j] = head->val;
23 head = head->next;
24 if (!head || ++cnt == size) break;
26 if (!valid(i + offset[direction].first, j + offset[direction].second)) {
27 limit[direction] += limit_offset[direction];
28 direction = (direction + 1) % 4;
29 }
31 i += offset[direction].first;
32 j += offset[direction].second;
33 }
35 return res;
36 }
37 };