BackendML

Spiral Matrix

Medium2 min read
The Spiral Matrix problem requires traversing all elements of a matrix in spiral order.

Problem

You are given an m × n matrix. Return all elements of the matrix in spiral order, starting from the top-left corner and moving right, then down, then left, and then up repeatedly toward the center.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

matrix = [ [1,2,3], [4,5,6], [7,8,9] ]

Output

[1,2,3,6,9,8,7,4,5]

Solution

This problem can be solved using a Boundary Traversal approach.

We maintain four boundaries: top, bottom, left, and right. These boundaries represent the remaining portion of the matrix that has not yet been traversed.

We first traverse the top row from left to right and move top down. Then, we traverse the right column from top to bottom and move right left.

If rows are still remaining, we traverse the bottom row from right to left and move bottom up. If columns are still remaining, we traverse the left column from bottom to top and move left right.

We continue this process until the boundaries cross.
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();

        int rows = matrix.length;
        int columns = matrix[0].length;

        int left = 0;
        int top = 0;
        int right = columns - 1;
        int bottom = rows - 1;

        while (left <= right && top <= bottom) {

            // Traverse top row
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            top++;

            // Traverse right column
            if (top <= bottom) {
                for (int i = top; i <= bottom; i++) {
                    result.add(matrix[i][right]);
                }
            }
            right--;

            // Traverse bottom row
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }
            }
            bottom--;

            // Traverse left column
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
            }
            left++;
        }

        return result;
    }
}

Complexity

Each matrix element is visited exactly once, resulting in O(n × m) time complexity, and only four boundary variables are used apart from the output list, resulting in O(1) extra space.

Comments

No comments yet. Ask a question or share what helped.