diff --git a/2326. Spiral Matrix IV b/2326. Spiral Matrix IV new file mode 100644 index 0000000..9bc6584 --- /dev/null +++ b/2326. Spiral Matrix IV @@ -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> spiralMatrix(int n, int m, ListNode* head) { + vector> ans(n,vector (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; + } +};