-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathSpiral Matrix IV.cpp
65 lines (64 loc) · 1.82 KB
/
Spiral Matrix IV.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
public:
vector<vector<int>> spiralMatrix(int n, int m, ListNode* head)
{
// Create a matrix of n x m with values filled with -1.
vector<vector<int>> spiral(n, vector<int>(m, -1));
int i = 0, j = 0;
// Traverse the matrix in spiral form, and update with the values present in the head list.
// If head reacher NULL pointer break out from the loop, and return the spiral matrix.
while (head != NULL)
{
if (j < m)
{
while (head != NULL && j < m && spiral[i][j] == -1)
{
spiral[i][j] = head->val;
head = head->next;
j++;
}
if (head == NULL)
break;
i++;
j--;
}
if (i < n)
{
while (head != NULL && i < n && spiral[i][j] == -1)
{
spiral[i][j] = head->val;
head = head->next;
i++;
}
i--;
j--;
}
if (j >= 0)
{
while (head != NULL && j >= 0 && spiral[i][j] == -1)
{
spiral[i][j] = head->val;
head = head->next;
j--;
}
j++;
i--;
}
if (i >= 0)
{
while (head != NULL && i >= 0 && spiral[i][j] == -1)
{
spiral[i][j] = head->val;
head = head->next;
i--;
}
i++;
j++;
}
n--;
m++;
}
// Rest values are itself -1.
return spiral;
}
};