generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
49 lines (40 loc) · 1.07 KB
/
solution.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
#include <vector>
class Solution {
public:
std::vector<std::vector<int>> spiralMatrix(int m, int n, ListNode* head) {
std::vector<std::vector<int>> output(m, std::vector(n, -1));
int y{0}, x{-1};
for (int i{n}; i > 0; --i) {
if (head == nullptr) return output;
output[y][++x] = head->val;
head = head->next;
}
--m, --n;
while (m > 0 || n > 0) {
for (int i{m}; i > 0; --i) {
if (head == nullptr) return output;
output[++y][x] = head->val;
head = head->next;
}
for (int i{n}; i > 0; --i) {
if (head == nullptr) return output;
output[y][--x] = head->val;
head = head->next;
}
--m, --n;
if (m <= 0 && n <= 0) break;
for (int i{m}; i > 0; --i) {
if (head == nullptr) return output;
output[--y][x] = head->val;
head = head->next;
}
for (int i{n}; i > 0; --i) {
if (head == nullptr) return output;
output[y][++x] = head->val;
head = head->next;
}
--m, --n;
}
return output;
}
};