Algo-Sim › Matrix & Bit Manipulation

Spiral Matrix

Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

List a matrix in clockwise spiral order by walking the outer ring and moving four boundaries inward.

Problem

Given an m × n matrix, return all of its values in clockwise spiral order: along the top row, down the right column, back along the bottom row, up the left column, then the same for the inner rings.

Constraints

Edge cases to test

Follow-up questions

How do you generate a spiral (fill 1..n²)?
Walk the same four boundaries and write a counter instead of reading (LC 59).
Is there a direction-vector version?
Turn right whenever the next cell is outside or visited; needs a visited marker or the boundary trick to stay O(1) extra.

Solution

Java

public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> out = new ArrayList<>();
    int top = 0, bottom = matrix.length - 1;
    int left = 0, right = matrix[0].length - 1;
    while (top <= bottom && left <= right) {
        for (int c = left; c <= right; c++) out.add(matrix[top][c]);
        top++;
        for (int r = top; r <= bottom; r++) out.add(matrix[r][right]);
        right--;
        if (top <= bottom) {
            for (int c = right; c >= left; c--) out.add(matrix[bottom][c]);
            bottom--;
        }
        if (left <= right) {
            for (int r = bottom; r >= top; r--) out.add(matrix[r][left]);
            left++;
        }
    }
    return out;
}

Python

def spiral_order(matrix):
    out = []
    top, bottom = 0, len(matrix) - 1
    left, right = 0, len(matrix[0]) - 1
    while top <= bottom and left <= right:
        for c in range(left, right + 1):
            out.append(matrix[top][c])
        top += 1
        for r in range(top, bottom + 1):
            out.append(matrix[r][right])
        right -= 1
        if top <= bottom:
            for c in range(right, left - 1, -1):
                out.append(matrix[bottom][c])
            bottom -= 1
        if left <= right:
            for r in range(bottom, top - 1, -1):
                out.append(matrix[r][left])
            left += 1
    return out

C++

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

class Solution {
  public:
    vector<int> spiralOrder(vector<vector<int>> &matrix) {
        vector<int> out = {};
        int top = 0, bottom = int(matrix.size()) - 1;
        int left = 0, right = int(matrix[0].size()) - 1;
        while (top <= bottom && left <= right) {
            for (int c = left; c <= right; c++)
                out.push_back(matrix[top][c]);
            top++;
            for (int r = top; r <= bottom; r++)
                out.push_back(matrix[r][right]);
            right--;
            if (top <= bottom) {
                for (int c = right; c >= left; c--)
                    out.push_back(matrix[bottom][c]);
                bottom--;
            }
            if (left <= right) {
                for (int r = bottom; r >= top; r--)
                    out.push_back(matrix[r][left]);
                left++;
            }
        }
        return out;
    }
};

More Matrix & Bit Manipulation problems