Spiral Matrix II

Updated on 24 June, 2025
Spiral Matrix II header image

Problem Statement

The task is to create a square matrix with dimensions n x n given a positive integer n. This matrix should be populated with the numbers from 1 to n^2. However, the unique requirement is that these numbers must be filled in a spiral order. Starting from the top-left corner, the numbers spiral inward towards the center in a clockwise fashion. This pattern presents an interesting challenge in matrix manipulation and iteration control as the matrix size grows with larger values of n.

Examples

Example 1

Input:

n = 3

Output:

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

Example 2

Input:

n = 1

Output:

[[1]]

Constraints

  • 1 <= n <= 20

Approach and Intuition

Generating the Spiral Matrix:

  1. Initial Setup:

    • Create an empty matrix of size n x n. This can be achieved using list comprehensions or nested loops. Each cell is initially marked with some placeholder or unassigned.
  2. Navigation Setup:

    • Define movement directions for the spiral traversal. Typically, the cycle is right -> down -> left -> up repeated until the matrix is filled.
  3. Boundary and State Control:

    • Keep track of the edges of the matrix (top, bottom, left, right). These boundaries will change whenever a row or a column is completely filled. For example, after moving right (filling top row), the top boundary shifts downward.
    • Control the traversal using a direction index, and change direction each time a boundary is reached or the next cell in the current direction is already filled.
  4. Filling the Matrix:

    • Start at the top-left corner ([0][0]) and begin with moving right.
    • Place numbers continuously in the matrix from 1 to n^2, adjusting the position and direction based on the current state and boundaries.
    • Change the traversal direction and update boundaries as necessary until all positions in the matrix are filled.
  5. Completion Check:

    • The loop can naturally end once the number to be placed exceeds n^2. At this point, each entry in the matrix from [0][0] to [n-1][n-1] will be filled as per the spiral rule.

Example Walk-through:

  • For n = 3:

    • Start at [0][0], move right across the top row: Place 1, 2, 3.
    • Shift direction to down and move along the last column: Place 4, 5.
    • Continue spiraling to the left on the bottom row and then up to finish the middle of the matrix.
    • The resulting matrix: [[1, 2, 3], [8, 9, 4], [7, 6, 5]].
  • For n = 1:

    • Only one element to place, resulting in: [[1]].

This approach ensures that we are constantly adjusting our boundaries and direction, effectively spiraling towards the center of the matrix. The constraints 1 <= n <= 20 are manageable with this method, ensuring all computations are contained within reasonable time and space complexity.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    vector<vector<int>> fillMatrix(int size) {
        vector<vector<int>> matrix(size, vector<int>(size));
        int number = 1;
        for (int level = 0; level < (size + 1) / 2; level++) {
            // fill rightwards
            for (int i = level; i < size - level; i++) {
                matrix[level][i] = number++;
            }
            // fill downwards
            for (int i = level + 1; i < size - level; i++) {
                matrix[i][size - level - 1] = number++;
            }
            // fill leftwards
            for (int i = size - level - 2; i >= level; i--) {
                matrix[size - level - 1][i] = number++;
            }
            // fill upwards
            for (int i = size - level - 2; i > level; i--) {
                matrix[i][level] = number++;
            }
        }
        return matrix;
    }
};

The problem solution provided involves generating a square matrix filled with numbers from 1 to n^2 in a spiral order, where n is specified by the size parameter of the fillMatrix function. Developed in C++, the code is structured within a Solution class.

Key insights of the implementation include:

  • Create a matrix with dimensions size x size, initialized with zeros.

  • Use a four-step loop to fill the matrix:

    • Fill rightwards: Populate the top row from left to right.
    • Fill downwards: Populate the last column from top to bottom.
    • Fill leftwards: Populate the bottom row from right to left.
    • Fill upwards: Populate the first column from bottom to top.
  • Each of these filling steps is bound by level, which ensures internal spirals are correctly populated as the matrix builds from the outer layers towards the center.

The function returns the populated matrix, making it easily accessible for verification or for further processing in other parts of your application. This approach effectively addresses the problem requirements while maintaining clarity and operational efficiency.

java
class MatrixGenerator {
    public int[][] spiralMatrix(int size) {
        int[][] matrix = new int[size][size];
        int num = 1;
        for (int level = 0; level < (size + 1) / 2; level++) {
            // moving right
            for (int i = level; i < size - level; i++) {
                matrix[level][i] = num++;
            }
            // moving down
            for (int i = level + 1; i < size - level; i++) {
                matrix[i][size - level - 1] = num++;
            }
            // moving left
            for (int i = level + 1; i < size - level; i++) {
                matrix[size - level - 1][size - i - 1] = num++;
            }
            // moving up
            for (int i = level + 1; i < size - level - 1; i++) {
                matrix[size - i - 1][level] = num++;
            }
        }
        return matrix;
    }
}

Problem Title: Spiral Matrix II

Language: Java

Solution Summary:

The Java code defines a class MatrixGenerator with a method spiralMatrix that generates a square matrix filled with numbers arranged in a spiral order. The matrix's size is determined by the input parameter size. The methodology is divided into four directional movements to fill the matrix in the required spiral order.

  1. Initialize a 2D array matrix of size [size][size] and a variable num to track the current number being placed in the matrix.
  2. Use a loop to handle the filling of the matrix layer by layer. This loop runs from the outermost layer to the innermost, based on the variable level.
  3. In each iteration of the loop, handle matrix filling in these directions:
    • Right: Incrementally fill positions from the current level index to size - level, at the top of the current level.
    • Down: Move down the right side of the current square from the next row at the current level up to size - level.
    • Left: Move left at the bottom of the current square from right to left.
    • Up: Move up the left side of the current square, completing the spiral cycle for the current level.
  4. Repeat these steps for each level until numbers are filled, and return the matrix.

This approach efficiently fills a 2D matrix in a spiral order, optimizing operations based on the matrix's size and ensuring completeness with each loop cycle handling all sides of the current spiral level. This technique ensures all cells in the matrix are filled exactly once, maintaining an O(n^2) complexity, where n is the dimension of the matrix and the number of elements to insert.

c
int** createSpiralMatrix(int size, int* matrixSize, int** columnSizes) {
    int** matrix = (int**)malloc(size * sizeof(int*));
    *matrixSize = size;
    *columnSizes = (int*)malloc(size * sizeof(int));
    for (int i = 0; i < size; i++) {
        matrix[i] = (int*)malloc(size * sizeof(int));
        (*columnSizes)[i] = size;
    }
    int number = 1;
    for (int level = 0; level < (size + 1) / 2; level++) {
        for (int idx = level; idx < size - level; idx++) {
            matrix[level][idx] = number++;
        }
        for (int idx = level + 1; idx < size - level; idx++) {
            matrix[idx][size - level - 1] = number++;
        }
        for (int idx = size - level - 2; idx >= level; idx--) {
            matrix[size - level - 1][idx] = number++;
        }
        for (int idx = size - level - 2; idx > level; idx--) {
            matrix[idx][level] = number++;
        }
    }
    return matrix;
}

The given C function createSpiralMatrix is designed to generate a square matrix filled with integers from 1 to size * size in a spiral order. The implementation efficiently manages memory allocation and matrix population, ensuring error-free filling by handling different directions of the spiral within nested loops.

Follow these steps to comprehend how the function achieves the task:

  1. Initialize and allocate memory dynamically for the 2D matrix using malloc. Each row in the matrix equally receives an allocation for size integers.

  2. Utilize four nested for loops to fill the matrix in the spiral order, which are:

    • The first loop determines the outer boundary or the level of the spiral to be filled.
    • Inside each level, four loops manage the direction-specific filling:
      • Rightward across the top of the current level.
      • Downward along the right side of the current square or level.
      • Leftward on the bottom from right to left.
      • Upward on the left side, finishing below the start of the top right fill.
  3. Each filled value in the matrix increments sequentially, starting from 1 and counting up through the final value of size * size.

  4. The matrix is finally returned, with each row having a uniformly set column size indicative of a well-formed square matrix.

This method is efficient and straightforward, integrating control structures and memory management to accomplish the matrix creation task. Moreover, the spiral filling algorithm is precisely coordinated to ensure the correct order of number insertion and to avoid overlap or unfilled entries within the matrix.

js
var createSpiralMatrix = function(size) {
    let matrix = Array.from({ length: size }, () => Array(size).fill(0));
    let num = 1;
    for (let level = 0; level < Math.floor((size + 1) / 2); level++) {
        // Fill left to right
        for (let i = level; i < size - level; i++) {
            matrix[level][i] = num++;
        }
        // Fill top to bottom
        for (let j = level + 1; j < size - level; j++) {
            matrix[j][size - level - 1] = num++;
        }
        // Fill right to left
        for (let i = size - level - 2; i >= level; i--) {
            matrix[size - level - 1][i] = num++;
        }
        // Fill bottom to top
        for (let j = size - level - 2; j > level; j--) {
            matrix[j][level] = num++;
        }
    }
    return matrix;
};

The provided JavaScript function createSpiralMatrix generates a square matrix filled with integers in a spiral order, taking size as an input that determines the dimensions of the matrix (i.e., size x size). The logic involves creating a square matrix initially filled with zeros. The filling process is structured into four main loops which cover the spiral's left to right, top to bottom, right to left, and bottom to top movements:

  • Initially, the matrix is created using Array.from with each inner array filled with zeros.
  • A nested loop structure, based on level, controls the entry of numbers into the matrix. The outer loop divides the matrix into levels, where each level corresponds to a complete lap around the outer edge of the remaining unsubscribed matrix.
  • The first nested loop fills the numbers from left to right in the topmost row of the current level.
  • The second nested loop fills numbers from top to bottom along the rightmost column of the current level.
  • The third loop fills numbers from right to left in the bottom row of the current level.
  • The fourth and final loop completes the current spiral by filling numbers from bottom to top along the leftmost column.
  • The function then increments the number each time a new integer is placed in the matrix.

As num starts at 1 and is incremented after assigning to a matrix cell, the matrix is filled with integers from 1 to size*size. The number placement spirals inward until the entire matrix is filled, returning the complete matrix filled in a spiral order. Ensure to properly understand the iterative handling of the matrix indices to visualize the spiral pattern accurately. This solution effectively manages to simulate the spiral pattern using a tiered loop approach that incrementally restricts the operational area.

python
class MatrixGenerator:
    def spiralOrderMatrix(self, size: int) -> list[list[int]]:
        matrix = [[0] * size for i in range(size)]
        num = 1
        for level in range((size + 1) // 2):
            # rightward
            for i in range(level, size - level):
                matrix[level][i] = num
                num += 1
            # downward
            for i in range(level + 1, size - level):
                matrix[i][size - level - 1] = num
                num += 1
            # leftward
            for i in range(size - level - 2, level - 1, -1):
                matrix[size - level - 1][i] = num
                num += 1
            # upward
            for i in range(size - level - 2, level, -1):
                matrix[i][level] = num
                num += 1
        return matrix

The provided Python code defines a class MatrixGenerator with a method spiralOrderMatrix which generates an n x n spiral matrix with integers from 1 to n^2 using a layered approach.

  • Initialize an n x n matrix of zeroes.
  • Use a layered (or level-wise) loop. For each layer:
    • Fill the top row of the current layer from left to right.
    • Fill the right column of the current layer from top to bottom.
    • Fill the bottom row of the current layer from right to left.
    • Fill the left column of the current layer from bottom to top.

This method efficiently fills up the matrix in a spiral order while incrementing values from 1 up to n^2. Each sub-step strictly adheres to filling specific parts of the current layer, ensuring no overlaps occur and all cells are filled precisely once. The layered nature of the operations allows the method to gracefully handle both odd and even dimensions of the matrix.

Comments

No comments yet.