2326. Spiral Matrix IV

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> spiralMatrix(int m, int n, ListNode* head)
    {
        int i = 0, j = 0, dir = 0;

        int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

        vector<vector<int>> res(m, vector<int>(n, -1));

        while (head)
        {
            res[i][j] = head->val;
            int new_i = i + directions[dir][0];
            int new_j = j + directions[dir][1];

            if (new_i < 0 || new_j < 0 || new_i >= m || new_j >= n || res[new_i][new_j] != -1)
            {
                dir = (dir + 1) % 4;
            }
            i += directions[dir][0];
            j += directions[dir][1];
            head = head->next;
        }

        return res;
    }
};
  • T: O()O()
  • S: O()O()