leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

spiral-matrix.dart (1603B)


      1 //Given a matrix return the values contained within it
      2 //as a list in the order of a spiral.
      3 //Ex:
      4 // 1 2 3
      5 // 4 5 6
      6 // 7 8 9
      7 //Output:
      8 // [1,2,3,6,9,8,7,4,5]
      9 //To know when to end my code counts the number of spaces that I
     10 //have visited to see if I have gone to all of them. When I have 
     11 //the algorithm returns the list.
     12 //The time complexity of this code is O(n) where n is the h*w of the matrix
     13 //Time: 251ms Beats: 65.38%
     14 //Memory: 140.1MB Beats: 61.54%
     15 
     16 class Solution {
     17   List<int> spiralOrder(List<List<int>> matrix) {
     18       int margin_top = 0;
     19       int margin_bottom = matrix.length;
     20       int margin_right = matrix[0].length;
     21       int margin_left = 0;
     22       int rem = matrix.length * matrix[0].length;
     23       List<int> return_vals = [];
     24       while(rem > 0){
     25           for(int i = margin_left ; i < margin_right && rem != 0  ; ++i){
     26               return_vals.add(matrix[margin_top][i]);
     27               rem -= 1;
     28           }
     29           margin_top += 1;
     30           for(int i = margin_top ; i < margin_bottom && rem != 0  ; ++i){
     31               return_vals.add(matrix[i][margin_right - 1]);
     32               rem -= 1;
     33           }
     34           margin_right -= 1;
     35           for(int i = margin_right - 1; i >= margin_left && rem != 0  ; --i){
     36               return_vals.add(matrix[margin_bottom - 1][i]);
     37               rem -= 1;
     38           }
     39           margin_bottom -= 1;
     40           for(int i = margin_bottom - 1; i >= margin_top && rem != 0 ; --i){
     41               return_vals.add(matrix[i][margin_left]);
     42               rem -= 1;
     43           }
     44           margin_left += 1;
     45       }
     46       return return_vals;
     47   }
     48 }
     49