mediumArrays & Matrix (Must-Do)

Spiral Matrix

Read a rectangular matrix in a clockwise spiral, starting at its top-left corner and moving right first.

Work through the cases

3 examples

Input notation

Space-separated matrix rows, one per line.

Expected result

Visited values separated by spaces.
Case 1

Input

1 2 3
4 5 6

Expected output

1 2 3 6 5 4
Case 2

Input

8
9

Expected output

8 9
Case 3

Input

1 2 3

Expected output

1 2 3

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

The first idea is to peel layers: four loops per layer for top, right, bottom, left, then shrink the bounds. m, n ≤ 10 would pass, but a leftover single row or column is easy to get wrong. The waste is hand-managing four edges. A spiral is: keep the current direction, and turn right when the next cell is out of bounds or already visited. So we cycle four directions and mark visited cells in vis, taking m × n steps.

We can simulate the entire traversal process. We use i and j to represent the row and column of the current element being visited, and k to represent the current direction. We use an array or hash table vis to record whether each element has been visited. Each time we visit an element, we mark it as visited, then move one step forward in the current direction. If moving forward results in an out-of-bounds condition or the element has already been visited, we change direction and continue moving forward until the entire matrix has been traversed.

The time complexity is O(m × n), and the space complexity is O(m × n). Here, m and n are the number of rows and columns of the matrix, respectively.

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        int[] dirs = {0, 1, 0, -1, 0};
        int i = 0, j = 0, k = 0;
        List<Integer> ans = new ArrayList<>();
        boolean[][] vis = new boolean[m][n];
        for (int h = m * n; h > 0; --h) {
            ans.add(matrix[i][j]);
            vis[i][j] = true;
            int x = i + dirs[k], y = j + dirs[k + 1];
            if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) {
                k = (k + 1) % 4;
            }
            i += dirs[k];
            j += dirs[k + 1];
        }
        return ans;
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.

Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.