Start learning free

LESSON 50 OF 314 · MATRIX

Spiral Matrix in C#: Walking Four Shrinking Boundaries

Practice O(m*n) Read the full explanation

You get a grid matrix of integers, with m rows and n columns.

Return a List of its values in spiral order.

matrix is an array of rows. Each row is an array of integers. Row 0 is the top row. Column 0 is the leftmost column.

The spiral starts at the top-left value and goes clockwise around the edge. It goes right along the top row, then down the right column. Then it goes left along the bottom row and up the left column.

Next, it does the same with the smaller grid inside, and so on. It takes each value exactly once.

 

Example 1:

Input: matrix = [
  [5, 1, 8],
  [0, 3, 2],
  [9, 7, 4]
]
Output: [5, 1, 8, 2, 4, 7, 9, 0, 3]
Explanation: The spiral first goes around the edge:
5, 1 and 8 across the top,
2 and 4 down the right side,
7 and 9 back along the bottom,
0 up the left side.
3 is left in the middle.

Example 2:

Input: matrix = [
  [3, -1, 7],
  [6, 0, 2],
  [1, 5, 9],
  [8, 8, 4]
]
Output: [3, -1, 7, 2, 9, 4, 8, 8, 1, 6, 0, 5]
Explanation: The spiral first goes around the edge:
3, -1 and 7 across the top,
2, 9 and 4 down the right side,
8 and 8 back along the bottom,
1 and 6 up the left side.
Inside, one column is left.
It gives 0, then the 5 below it.

Example 3:

Input: matrix = [
  [-4, 0, 4]
]
Output: [-4, 0, 4]
Explanation: There is only one row.
The spiral goes right along it and stops.
No value is taken twice.

 

Constraints:

  • m and n are each from 1 to 500.
  • Each value is an integer from -1000 to 1000.
  • Negative values and repeats are allowed.

Note:

Your algorithm should run in O(m * n) time: it visits every element once.

STEP 1 OF 19
    Ctrl + Enter to check

    C# · MATRIX

    Spiral Matrix in C#, explained

    Problem overview

    The method SpiralOrder receives a matrix as an int[][], with m rows and n columns, and returns a List<int> of all its elements in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: along the top row to the right, down the right column, back along the bottom row to the left, and up the left column. It then repeats on whatever is left inside, until every element has been visited exactly once. The method should run in O(m * n) time.

    For {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} the result is [1, 2, 3, 6, 9, 8, 7, 4, 5]: the outer ring, then the single element 5 left in the middle. For a matrix with 3 rows and 4 columns the second ring is a single row, 6, 7, which is read left to right.

    Approach: four boundaries that move inward

    There is no clever formula here: the idea is to keep track of which rectangle is still unvisited. Four integers describe it: top and bottom are the first and last unvisited rows, and left and right are the first and last unvisited columns. Each lap walks the four sides of that rectangle in clockwise order, and every time a side is finished, its boundary moves one step inward. The loop ends when a pair of boundaries crosses, because then nothing is left.

    Visiting each element once makes this O(m * n). The alternative, marking visited cells in a second matrix and turning right whenever the next cell is taken, works too but needs extra memory. The boundaries need only four variables.

    The only delicate part is a rectangle that has become a single row or a single column. Then the "bottom side" is the same row as the top side, and the "left side" is the same column as the right side. Walking them would visit those elements a second time. The two if checks guard exactly that.

    Tracing the 3x4 matrix {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} shows the boundaries at work. The first lap starts with top = 0, bottom = 2, left = 0, right = 3 and adds 1, 2, 3, 4, 8, 12, 11, 10, 9, 5. The second lap starts with top = 1, bottom = 1, left = 1, right = 2: a single row. It adds 6, 7, and then the boundaries end at top = 2, bottom = 1, left = 2, right = 1, so the loop condition fails. In that second lap, the top-side walk reads the row, top++ pushes top past bottom, and the bottom-side if is skipped.

    Step by step

    1. Create the empty list result that collects elements in visiting order.
    2. Set the row boundaries: top = 0 and bottom = matrix.Length - 1.
    3. Set the column boundaries: left = 0 and right = matrix[0].Length - 1. All rows have the same length, so the first row tells how many columns there are.
    4. Loop while top <= bottom && left <= right. As long as neither pair has crossed, there are unvisited cells.
    5. Top side: walk col from left to right, adding matrix[top][col]. Then do top++. Moving top immediately keeps the top-right corner from being added again by the next side.
    6. Right side: walk row from top (already moved) to bottom, adding matrix[row][right]. Then do right--.
    7. Bottom side, only if top <= bottom: walk col from right down to left, adding matrix[bottom][col], then do bottom--. If only one row was left, the top-side walk already read it, and top has gone past bottom.
    8. Left side, only if left <= right: walk row from bottom up to top, adding matrix[row][left], then do left++. If only one column was left, the right-side walk already read it.
    9. Return result after the loop.

    The solution in C#

    class Solution {
        public List<int> SpiralOrder(int[][] matrix) {
            List<int> result = new List<int>();
            int top = 0, bottom = matrix.Length - 1;
            int left = 0, right = matrix[0].Length - 1;
            while (top <= bottom && left <= right) {
                for (int col = left; col <= right; col++) {
                    result.Add(matrix[top][col]);
                }
                top++;
                for (int row = top; row <= bottom; row++) {
                    result.Add(matrix[row][right]);
                }
                right--;
                if (top <= bottom) {
                    for (int col = right; col >= left; col--) {
                        result.Add(matrix[bottom][col]);
                    }
                    bottom--;
                }
                if (left <= right) {
                    for (int row = bottom; row >= top; row--) {
                        result.Add(matrix[row][left]);
                    }
                    left++;
                }
            }
            return result;
        }
    }
    

    C# details worth knowing:

    • List<int> lives in System.Collections.Generic, so a standalone file needs using System.Collections.Generic;. A list grows as you Add, unlike an array whose length is fixed when it is created.
    • Several variables in one declaration. int top = 0, bottom = matrix.Length - 1; declares two int variables, each with its own initial value.
    • Jagged array. int[][] is an array of row arrays, so the row count is matrix.Length and the column count is matrix[0].Length, and cells are read as matrix[row][col].
    • The input is only read. Unlike in-place matrix problems, nothing in matrix changes.

    Complexity

    Time: O(m * n). Each element is added exactly once, and the checks around the loops add constant work per lap.

    Space: O(1) extra, apart from the returned list, which holds all m * n elements.

    Edge cases and common mistakes

    • A single row. {{1, 2, 3}} returns [1, 2, 3]. After the top side, top becomes 1 and bottom is 0, so the bottom side is skipped.
    • A single column. {{3}, {2}, {1}} returns [3, 2, 1]. After the right side, right drops below left, so the left side is skipped.
    • A single element. {{4}} returns [4].
    • A 2x2 matrix. {{1, 2}, {3, 4}} returns [1, 2, 4, 3].
    • Not rectangular. A square-only solution that uses n for both dimensions would break on a 3x4 matrix. Keep separate row and column boundaries.
    • Skipping the two if checks. On one remaining row or column, the last two sides repeat elements and the list ends up with duplicates.
    • Moving a boundary late. If top++ comes after the right-side loop, the top-right corner is added twice.

    Testing

    • {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} gives [1, 2, 3, 6, 9, 8, 7, 4, 5].
    • {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} gives [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].
    • {{3}, {2}, {1}} gives [3, 2, 1].
    • {{1, 2, 3}} gives [1, 2, 3].
    • {{1, 2}, {3, 4}} gives [1, 2, 4, 3].
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free