Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

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

Example 2:

Input: matrix = [[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]

Constraints:

  • m == matrix.length

  • n == matrix[i].length

  • 1 <= m, n <= 10

  • -100 <= matrix[i][j] <= 100

Solutions

public class Solution
{
    public IList<int> SpiralOrder(int[][] matrix)
    {
        List<int> result = new();
        if (matrix.Length > 0)
        {

            int top = 0, bottom = matrix.Length - 1;
            int left = 0, right = matrix[0].Length - 1;
            int dir = 0; // 0: right, 1: down, 2: left, 3: up


            while (top <= bottom && left <= right)
            {
                if (dir == 0)
                { 
                    // Move right
                    for (int i = left; i <= right; i++) result.Add(matrix[top][i]);
                    top++;
                }
                else if (dir == 1)
                { 
                    // Move down
                    for (int i = top; i <= bottom; i++) result.Add(matrix[i][right]);
                    right--;
                }
                else if (dir == 2)
                { 
                    // Move left
                    for (int i = right; i >= left; i--) result.Add(matrix[bottom][i]);
                    bottom--;
                }
                else if (dir == 3)
                { 
                    // Move up
                    for (int i = bottom; i >= top; i--) result.Add(matrix[i][left]);
                    left++;
                }
                dir = (dir + 1) % 4; // Change direction
            }
        }
        return result;
    }

}

The time complexity is still O(mn), and the space complexity is O(1) excluding the output. This is because it does not use any additional data structures whose size depends on the input. The output size is O(mn), as it includes all elements of the matrix. This version of the method

Last updated