Skip to content

Commit

Permalink
Create 2326. Spiral Matrix IV (#580)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Sep 9, 2024
2 parents 544f7d8 + 2804e2d commit 2ab8fab
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions 2326. Spiral Matrix IV
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* 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:
vector<vector<int>> spiralMatrix(int n, int m, ListNode* head) {
vector<vector<int>> ans(n,vector<int> (m,-1));
int left=0;
int right=m-1;
int top=0;
int bottom=n-1;
ListNode* temp=head;
while (top<=bottom && left<=right){
for(int i=left;i<=right && temp;i++){
ans[top][i]=temp->val;
temp=temp->next;
}
top++;
for(int i=top;i<=bottom && temp;i++){
ans[i][right]=temp->val;
temp=temp->next;
}
right--;
if(top<=bottom){
for(int i=right;i>=left && temp;i--){
ans[bottom][i]=temp->val;
temp=temp->next;
}
bottom--;
}
if(left<=right){
for(int i=bottom;i>=top && temp;i--){
ans[i][left]=temp->val;
temp=temp->next;
}
left++;
}
}
return ans;
}
};

0 comments on commit 2ab8fab

Please sign in to comment.