Blogs Hub

by Sumit Chourasia | Oct 27, 2020 | Category :coding | Tags : algorithm array data-structure leetcode medium

Spiral Matrix - Array - Medium - LeetCode

Spiral Matrix - Array - Medium - LeetCode

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

public class Solution {
    public IList<int> SpiralOrder(int[][] matrix) {
        
        var res = new List<int>();
        
        if(matrix.Length==0){
            return res;
        }
        
        int sx = 0;
        int ex = matrix.Length;
        int sy = 0;
        int ey = matrix[0].Length;
                
        
        while (sx<ex && sy<ey){
            for(int i=sy;i<ey;i++){
                res.Add(matrix[sx][i]);
            }
            sx++;
            
            for(int i= sx;i<ex;i++){
                res.Add(matrix[i][ey-1]);
            }
            ey--;
            
            if(sx<ex){
                for(int i= ey-1;i>=sy;i--){
                    res.Add(matrix[ex-1][i]);
                }
            }
            ex--;
            
            if(sy<ey){
                for(int i=ex-1;i>=sx;i--){
                    res.Add(matrix[i][sy]);
                }
            }
            sy++;
        }
        
        return res;
    }
}

Time Complexity: O(n^2)

Space Complexity: O(1)