54. Spiral Matrix

Intitution

We need to simulate how a spiral moves through the matrix — from the top-left corner, moving right → down → left → up, and repeat while shrinking the boundaries.

To keep track of what’s been visited, we can shrink the four boundaries (top, bottom, left, right) after every full layer is traversed. This approach avoids using extra space for visited cells.

Complexity

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(nm)\text{O}(nm)

Code

public List<Integer> spiralOrder(int[][] matrix) {
    int totalElements = matrix.length * matrix[0].length;
    List<Integer> result = new ArrayList<>();

    int leftBound = 0, rightBound = matrix[0].length - 1;
    int topBound = 0, bottomBound = matrix.length - 1;

    while (totalElements > 0) {
        // Traverse from left to right
        for (int col = leftBound; col <= rightBound && totalElements > 0; col++) {
            result.add(matrix[topBound][col]);
            totalElements--;
        }
        topBound++;

        // Traverse from top to bottom
        for (int row = topBound; row <= bottomBound && totalElements > 0; row++) {
            result.add(matrix[row][rightBound]);
            totalElements--;
        }
        rightBound--;

        // Traverse from right to left
        for (int col = rightBound; col >= leftBound && totalElements > 0; col--) {
            result.add(matrix[bottomBound][col]);
            totalElements--;
        }
        bottomBound--;

        // Traverse from bottom to top
        for (int row = bottomBound; row >= topBound && totalElements > 0; row--) {
            result.add(matrix[row][leftBound]);
            totalElements--;
        }
        leftBound++;
    }

    return result;
}

Last updated