class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> ret(m, vector<int>(n, -1));
array<pair<int, int>, 4> adj = {make_pair(0,1), make_pair(1,0), make_pair(0,-1), make_pair(-1,0) };
for (int i = 0, j = 0, x = 0, y = 1, dir = 0; head != nullptr; i += x, j += y, head = head->next) {
ret[i][j] = head->val;
int next_x = i + x, next_y = j + y;
if (next_x < 0 || next_x >= m || next_y < 0 || next_y >= n || ret[next_x][next_y] != -1) {
dir = (dir + 1)%4;
std::tie(x, y) = adj[dir];
}
}
return ret;
}
};