22. 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]

Solution:

Using 4 pointer top, down, left, right And a direction pointer

class Solution
{
public:
    vector<int> spiralOrder(vector<vector<int>> &matrix)
    {

        vector<int> res;
        int n = matrix.size();
        int m = matrix[0].size();

        int top = 0;
        int down = n - 1;

        int left = 0;
        int right = m - 1;

        int dir = 0;
        
        while (top <= down && left <= right)
        {

            if (dir == 0)
            {
                for (int i = left; i <= right; i++)
                {
                    res.push_back(matrix[top][i]);
                }
                top++;
            }
            else if (dir == 1)
            {
                for (int i = top; i <= down; i++)
                {
                    res.push_back(matrix[i][right]);
                }
                right--;
            }
            else if (dir == 2)
            {
                for (int i = right; i >= left; i--)
                {
                    res.push_back(matrix[down][i]);
                }
                down--;
            }
            else if (dir == 3)
            {
                for (int i = down; i >= top; i--)
                {
                    res.push_back(matrix[i][left]);
                }
                left++;
            }
            
            dir = (dir + 1) % 4;
        }
        return res;
    }
};

Time Complexity: O(N)

Last updated

Was this helpful?