classSolution { public: vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) { vector<vector<int>> res(m, vector<int>(n, -1)); if (!head) return res; ListNode* p = head;
int left = 0; int right = n - 1; int up = 0; int down = m - 1; while (left <= right && up <= down) { // 从左到右 for (int j = left; j <= right; ++j) { if (!p) break; int val = p->val; p = p->next; res[up][j] = val; }
// 从上到下 for (int i = up + 1; i <= down; ++i) { if (!p) break; int val = p->val; p = p->next; res[i][right] = val; }
// 从右到左 for (int j = right - 1; j >= left; --j) { if (!p) break; int val = p->val; p = p->next; res[down][j] = val; }
// 从下到上 for (int i = down - 1; i > up; --i) { if (!p) break; int val = p->val; p = p->next; res[i][left] = val; }