Skip to content

Commit 2ab8fab

Browse files
authored
Create 2326. Spiral Matrix IV (#580)
2 parents 544f7d8 + 2804e2d commit 2ab8fab

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

2326. Spiral Matrix IV

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
vector<vector<int>> spiralMatrix(int n, int m, ListNode* head) {
14+
vector<vector<int>> ans(n,vector<int> (m,-1));
15+
int left=0;
16+
int right=m-1;
17+
int top=0;
18+
int bottom=n-1;
19+
ListNode* temp=head;
20+
while (top<=bottom && left<=right){
21+
for(int i=left;i<=right && temp;i++){
22+
ans[top][i]=temp->val;
23+
temp=temp->next;
24+
}
25+
top++;
26+
for(int i=top;i<=bottom && temp;i++){
27+
ans[i][right]=temp->val;
28+
temp=temp->next;
29+
}
30+
right--;
31+
if(top<=bottom){
32+
for(int i=right;i>=left && temp;i--){
33+
ans[bottom][i]=temp->val;
34+
temp=temp->next;
35+
}
36+
bottom--;
37+
}
38+
if(left<=right){
39+
for(int i=bottom;i>=top && temp;i--){
40+
ans[i][left]=temp->val;
41+
temp=temp->next;
42+
}
43+
left++;
44+
}
45+
}
46+
return ans;
47+
}
48+
};

0 commit comments

Comments
 (0)