Spiral matrix traversal

Read a matrix in a clockwise spiral by walking one shrinking ring of the border at a time.

Time O(rows × cols)Space O(1) extraCode C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Keep four walls - top, bottom, left, right - marking the unvisited ring. Walk the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top, then shrink every wall by one and repeat for the ring inside.

Code

public static List<int> SpiralOrder(int[,] mat) {
    int top = 0, bottom = mat.GetLength(0) - 1, left = 0, right = mat.GetLength(1) - 1;
    var res = new List<int>();
    while (top <= bottom && left <= right) {
        for (int c = left; c <= right; c++) res.Add(mat[top, c]);
        top++;
        for (int row = top; row <= bottom; row++) res.Add(mat[row, right]);
        right--;
        if (top <= bottom) {
            for (int c = right; c >= left; c--) res.Add(mat[bottom, c]);
            bottom--;
        }
        if (left <= right) {
            for (int row = bottom; row >= top; row--) res.Add(mat[row, left]);
            left++;
        }
    }
    return res;
}
static List<Integer> spiralOrder(int[][] mat) {
    int top = 0, bottom = mat.length - 1, left = 0, right = mat[0].length - 1;
    List<Integer> res = new ArrayList<>();
    while (top <= bottom && left <= right) {
        for (int c = left; c <= right; c++) res.add(mat[top][c]);
        top++;
        for (int row = top; row <= bottom; row++) res.add(mat[row][right]);
        right--;
        if (top <= bottom) {
            for (int c = right; c >= left; c--) res.add(mat[bottom][c]);
            bottom--;
        }
        if (left <= right) {
            for (int row = bottom; row >= top; row--) res.add(mat[row][left]);
            left++;
        }
    }
    return res;
}
vector<int> spiralOrder(const vector<vector<int>>& mat) {
    int top = 0, bottom = (int)mat.size() - 1, left = 0, right = (int)mat[0].size() - 1;
    vector<int> res;
    while (top <= bottom && left <= right) {
        for (int c = left; c <= right; c++) res.push_back(mat[top][c]);
        top++;
        for (int row = top; row <= bottom; row++) res.push_back(mat[row][right]);
        right--;
        if (top <= bottom) {
            for (int c = right; c >= left; c--) res.push_back(mat[bottom][c]);
            bottom--;
        }
        if (left <= right) {
            for (int row = bottom; row >= top; row--) res.push_back(mat[row][left]);
            left++;
        }
    }
    return res;
}
def spiral_order(mat: list[list[int]]) -> list[int]:
    top, bottom, left, right = 0, len(mat) - 1, 0, len(mat[0]) - 1
    res = []
    while top <= bottom and left <= right:
        for c in range(left, right + 1): res.append(mat[top][c])
        top += 1
        for row in range(top, bottom + 1): res.append(mat[row][right])
        right -= 1
        if top <= bottom:
            for c in range(right, left - 1, -1): res.append(mat[bottom][c])
            bottom -= 1
        if left <= right:
            for row in range(bottom, top - 1, -1): res.append(mat[row][left])
            left += 1
    return res

Tips

In the .NET library

The same four-wall technique also builds a spiral matrix from a list of numbers, just writing into mat instead of reading from it.