Back to solutions

Spiral Matrix

MediumMatrix

Return all elements of an m x n matrix in spiral order, starting from the top-left and moving clockwise.

Constraints
  • 1 <= m, n <= 10
  • matrix is m x n

Shrinking boundaries

Time O(m * n)Space O(1) extra

Keep four boundaries (top, bottom, left, right). Traverse the top row, right column, bottom row, and left column, shrinking the boundary after each pass until they cross.

#include <bits/stdc++.h>
using namespace std;

vector<int> spiralOrder(vector<vector<int>>& matrix) {
    vector<int> res;
    int top = 0, bottom = matrix.size() - 1;
    int left = 0, right = matrix[0].size() - 1;
    while (top <= bottom && left <= right) {
        for (int j = left; j <= right; j++) res.push_back(matrix[top][j]);
        top++;
        for (int i = top; i <= bottom; i++) res.push_back(matrix[i][right]);
        right--;
        if (top <= bottom) {
            for (int j = right; j >= left; j--) res.push_back(matrix[bottom][j]);
            bottom--;
        }
        if (left <= right) {
            for (int i = bottom; i >= top; i--) res.push_back(matrix[i][left]);
            left++;
        }
    }
    return res;
}