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#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

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;
}

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.