-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2326.cpp
More file actions
40 lines (40 loc) · 1.33 KB
/
2326.cpp
File metadata and controls
40 lines (40 loc) · 1.33 KB
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
/**
* 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:
int M;
int N;
vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
void nextPosition(vector<vector<int>>& matrix, int& currRow, int& currCol, int& direction) {
int nextRow = currRow + directions[direction][0];
int nextCol = currCol + directions[direction][1];
if (nextRow >= M || nextRow < 0 || nextCol >= N || nextCol < 0 || matrix[nextRow][nextCol] != -1) {
direction = (direction + 1) % 4;
}
currRow = currRow + directions[direction][0];
currCol = currCol + directions[direction][1];
}
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
M = m;
N = n;
vector<vector<int>> matrix(m, vector<int>(n, -1));
int currRow = 0;
int currCol = 0;
int direction = 0;
// 0: right; 1:down; 2:left; 3:up
while (head) {
matrix[currRow][currCol] = head->val;
nextPosition(matrix, currRow, currCol, direction);
head = head->next;
}
return matrix;
}
};