-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09sep.txt
40 lines (34 loc) · 1.25 KB
/
09sep.txt
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
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> matrix(m, vector<int>(n, -1));
int topRow = 0, bottomRow = m - 1, leftColumn = 0, rightColumn = n - 1;
while (head) {
// Fill top row
for (int col = leftColumn; col <= rightColumn && head; ++col) {
matrix[topRow][col] = head->val;
head = head->next;
}
topRow++;
// Fill right column
for (int row = topRow; row <= bottomRow && head; ++row) {
matrix[row][rightColumn] = head->val;
head = head->next;
}
rightColumn--;
// Fill bottom row
for (int col = rightColumn; col >= leftColumn && head; --col) {
matrix[bottomRow][col] = head->val;
head = head->next;
}
bottomRow--;
// Fill left column
for (int row = bottomRow; row >= topRow && head; --row) {
matrix[row][leftColumn] = head->val;
head = head->next;
}
leftColumn++;
}
return matrix;
}
};