[LeetCode] Spiral Matrix IV

2326. Spiral Matrix IV

You are given two integers m and n, which represent the dimensions of a matrix.

You are also given the head of a linked list of integers.

Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.

Return the generated matrix.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 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 n, int m, ListNode* head) {
vector<vector<int>> res(n, vector<int>(m, -1));
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1}, d = 1;
int y = 0, x = 0;
while(head) {
res[y][x] = head->val;
head = head->next;
for(int i = 0; i < 4; i++) {
int ny = y + dy[(d + i) % 4], nx = x + dx[(d + i) % 4];
if(0 <= ny and ny < n and 0 <= nx and nx < m and res[ny][nx] == -1) {
y = ny, x = nx, d = (d + i) % 4;
break;
}
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/03/PS/LeetCode/spiral-matrix-iv/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.