The Indian Engineer

Problem 54 Sprial Matrix

Posted on Last edited 3 mins

Array Matrix

Problem Statement

Link - Problem 54

Question

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

Example 1

image1

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

Example 2

image2

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

Solution

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        int cols = matrix[0].size();

        int row = 0, col = -1;

        int direc = 1;

        vector<int>ans;

        while(rows>0 && cols>0){
            for(int i = 0;i<cols;i++){
                col+=direc;
                ans.push_back(matrix[row][col]);
            }
            rows--;

            for(int i = 0;i<rows;i++){
                row+=direc;
                ans.push_back(matrix[row][col]);
            }
            cols--;

            direc*=-1;
        }
        return ans;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Matrix Traversal O(mn) O(1)

Explanation

1. Intuition

2. Implementation

The direction is changed by multiplying it by -1 because we need to change the direction from right to left and from left to right. The direction is changed only after traversing the row and the column. This is because we need to traverse the row and the column in the same direction.