spiral-matrix-ii.dart (1534B)
1 //Take a number as the input and return a matrix 2 //of the same width and height as the number where the 3 //values within it are ordered in a spiral formation. 4 //Ex. 5 //Input: 6 // 3 7 // 1 2 3 8 // 8 9 4 9 // 7 6 5 10 //The time complexity of this code is O(n^2) where n is the input number. 11 //Time: 260ms Beats: 75% 12 //Memory: 140.6MB Beats: 75% 13 14 class Solution { 15 List<List<int>> generateMatrix(int n) { 16 int placed = 1; 17 List<List<int>> spiral = []; 18 int top_margin = 0; 19 int bottom_margin = n; 20 int left_margin = 0; 21 int right_margin = n; 22 for(int i = 0 ; i < n ; ++i){ 23 spiral.add([]); 24 for(int x = 0 ; x < n ; ++x){ 25 spiral[spiral.length - 1].add(0); 26 } 27 } 28 while(placed < n*n + 1){ 29 for(int i = left_margin ; i < right_margin; ++i){ 30 spiral[top_margin][i] = placed; 31 placed += 1; 32 } 33 top_margin += 1; 34 35 for(int i = top_margin ; i < bottom_margin ; ++i){ 36 spiral[i][right_margin - 1] = placed; 37 placed += 1; 38 39 } 40 right_margin -= 1; 41 42 for(int i = right_margin - 1 ; i >= left_margin ; --i){ 43 spiral[bottom_margin - 1][i] = placed; 44 placed += 1; 45 46 } 47 bottom_margin -= 1; 48 49 for(int i = bottom_margin - 1; i >= top_margin ; --i){ 50 spiral[i][left_margin] = placed; 51 placed += 1; 52 53 } 54 left_margin += 1; 55 } 56 57 return spiral; 58 } 59 }