spiral-matrix-iv.dart (1944B)
1 //Take in an input of m and n where m is the height of the matrix and 2 //n is the width of the matrix. Then from there use a singly linked list 3 //and place the node's associated values into the matrix following a spiral pattern. 4 //All non-filled spaces should be -1. 5 //The time complexity of this code is O(m * n). 6 //Time: 563ms Beats: 100% 7 //Memory: 215.3MB Beats: 100% 8 //Not enough submissions to show metrics. 9 10 /** 11 * Definition for singly-linked list. 12 * class ListNode { 13 * int val; 14 * ListNode? next; 15 * ListNode([this.val = 0, this.next]); 16 * } 17 */ 18 class Solution { 19 List<List<int>> spiralMatrix(int m, int n, ListNode? head) { 20 int top_margin = 0; 21 int right_margin = n - 1; 22 int left_margin = 0; 23 int bottom_margin = m-1; 24 List<List<int>> return_list = []; 25 for(int i = 0 ; i < m; ++i){ 26 return_list.add([]); 27 for(int x = 0 ; x < n ; ++x){ 28 return_list[return_list.length - 1].add(-1); 29 } 30 } 31 while(head != null){ 32 for(int i = left_margin ; i <= right_margin ; ++i){ 33 return_list[top_margin][i] = (head?.val ?? return_list[top_margin][i]); 34 head = head?.next; 35 } 36 top_margin += 1; 37 for(int i = top_margin; i <= bottom_margin ; ++i){ 38 return_list[i][right_margin] = (head?.val ?? return_list[i][right_margin]); 39 head = head?.next; 40 } 41 right_margin-=1; 42 43 for(int i = right_margin ; i >= left_margin ; --i){ 44 return_list[bottom_margin][i] = (head?.val ?? return_list[bottom_margin][i]); 45 head = head?.next; 46 } 47 bottom_margin-=1; 48 for(int i = bottom_margin ; i >= top_margin ; --i){ 49 return_list[i][left_margin] = (head?.val ?? return_list[i][left_margin]); 50 head = head?.next; 51 } 52 left_margin += 1; 53 } 54 return return_list; 55 } 56 }