1
class Solution {
2
public:
3
vector<vector<int>> spiralMatrix(int n, int m, ListNode *head) {
4
// Create a matrix of n x m with values filled with -1.
5
vector<vector<int>> spiral(n, vector<int>(m, -1));
6
int i = 0, j = 0;
7
// Traverse the matrix in spiral form, and update with the values present in
8
// the head list. If head reacher NULL pointer break out from the loop, and
9
// return the spiral matrix.
10
while (head != NULL) {
11
if (j < m) {
12
while (head != NULL && j < m && spiral[i][j] == -1) {
13
spiral[i][j] = head->val;
14
head = head->next;
15
j++;
16
}
17
if (head == NULL) break;
18
i++;
19
j--;
20
}
21
if (i < n) {
22
while (head != NULL && i < n && spiral[i][j] == -1) {
23
spiral[i][j] = head->val;
24
head = head->next;
25
i++;
26
}
27
i--;
28
j--;
29
}
30
if (j >= 0) {
31
while (head != NULL && j >= 0 && spiral[i][j] == -1) {
32
spiral[i][j] = head->val;
33
head = head->next;
34
j--;
35
}
36
j++;
37
i--;
38
}
39
if (i >= 0) {
40
while (head != NULL && i >= 0 && spiral[i][j] == -1) {
41
spiral[i][j] = head->val;
42
head = head->next;
43
i--;
44
}
45
i++;
46
j++;
47
}
48
n--;
49
m++;
50
}
51
// Rest values are itself -1.
52
return spiral;
53
}
54
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0