HomeUncategorizedSpiral Matrix II Solution in Java | Spiral Matrix 2 | Leet...

Spiral Matrix II Solution in Java | Spiral Matrix 2 | Leet code solution

Published on

spot_img

The “Spiral Matrix II” problem is another variation of the original Spiral Matrix problem. In this version, instead of traversing an existing matrix, you’re asked to generate a new matrix of size n x n where each cell is filled in a spiral order. Let’s dive into a detailed explanation with examples.

Problem Statement:
Given a positive integer n, generate a square matrix of size n x n filled with elements from 1 to n^2 in a spiral order.

Example:
For example, if n = 3, the expected output would be:

 1  2  3
 8  9  4
 7  6  5

The numbers are filled in a spiral order starting from 1 and going up to 9.

Approach:
To solve the Spiral Matrix II problem, you can follow these steps:

  1. Initialize an empty n x n matrix with all elements set to 0.
  2. Initialize four variables: top, bottom, left, and right to define the boundaries of the current spiral. Initially, top = 0, bottom = n - 1, left = 0, and right = n - 1.
  3. Create a loop that runs while the boundaries (top, bottom, left, right) don’t overlap.
  4. Fill in the top boundary from left to right with consecutive numbers.
  5. Fill in the right boundary from top + 1 to bottom with consecutive numbers.
  6. Fill in the bottom boundary from right - 1 to left with consecutive numbers.
  7. Fill in the left boundary from bottom - 1 to top + 1 with consecutive numbers.
  8. Increment the number to be filled next.
  9. Repeat steps 4 to 8 until the boundaries overlap.
  10. The matrix is now filled in a spiral order.

Java Code with Explanation:
Here’s a Java code implementation of the above approach:

public class SpiralMatrix2 {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int num = 1;
        int top = 0, bottom = n - 1, left = 0, right = n - 1;

        while (num <= n * n) {
            for (int i = left; i <= right; i++) {
                matrix[top][i] = num++;
            }
            top++;

            for (int i = top; i <= bottom; i++) {
                matrix[i][right] = num++;
            }
            right--;

            for (int i = right; i >= left; i--) {
                matrix[bottom][i] = num++;
            }
            bottom--;

            for (int i = bottom; i >= top; i--) {
                matrix[i][left] = num++;
            }
            left++;
        }

        return matrix;
    }

    public static void main(String[] args) {
        SpiralMatrix2 spiralMatrix = new SpiralMatrix2();
        int n = 3;
        int[][] result = spiralMatrix.generateMatrix(n);
        for (int[] row : result) {
            for (int num : row) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
}

Explanation:
This code generates an n x n matrix filled with consecutive numbers in a spiral order. The loops fill in the top, right, bottom, and left boundaries sequentially until all elements are filled.

You can run this code with different values of n to generate spiral matrices of various sizes.

Conclusion:
The Spiral Matrix II problem is an interesting variation that requires careful handling of boundaries and iteration. By understanding the spiral order pattern and following the algorithmic approach, you can generate spiral matrices efficiently.

Thank You!

Latest articles

Amazon Digital Marketing Strategy: How It Dominates Online Sales

Discover how Amazon Digital Marketing Strategy helps dominate Online Sales using SEO, data-driven marketing, personalization, and advertising. Learn key strategies every digital marketer in 2026 can apply to grow business and boost online success.

SEO Experiment: Internal Linking Strategy That Boosted Rankings

This SEO Experiment reveals how a powerful Internal Linking Strategy helped boost rankings, improve website structure, and increase organic traffic. Learn simple and effective techniques used by a digital marketer in 2026 to achieve better SEO results and grow with smart digital marketing services.

SEO Experiment: AI Content vs Human Content – Who Wins?

This SEO Experiment compares AI Content and human-written content to find which performs better in search rankings. Discover how a digital marketer in 2026 can use the right strategy to improve Organic Traffic and deliver better digital marketing services.

Programmatic SEO Case Study: Scaling Organic Traffic with Automation

Learn how Programmatic SEO helps a digital marketer in 2026 scale organic traffic using automation. This case study explains strategies, tools, and methods used by digital marketing services to rank thousands of pages and grow website traffic fast.

More like this

Amazon Digital Marketing Strategy: How It Dominates Online Sales

Discover how Amazon Digital Marketing Strategy helps dominate Online Sales using SEO, data-driven marketing, personalization, and advertising. Learn key strategies every digital marketer in 2026 can apply to grow business and boost online success.

SEO Experiment: Internal Linking Strategy That Boosted Rankings

This SEO Experiment reveals how a powerful Internal Linking Strategy helped boost rankings, improve website structure, and increase organic traffic. Learn simple and effective techniques used by a digital marketer in 2026 to achieve better SEO results and grow with smart digital marketing services.

SEO Experiment: AI Content vs Human Content – Who Wins?

This SEO Experiment compares AI Content and human-written content to find which performs better in search rankings. Discover how a digital marketer in 2026 can use the right strategy to improve Organic Traffic and deliver better digital marketing services.