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