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

How to Manage Social Media Profiles Using AI Tools (Posts, Reels & Shorts Complete Guide)

Managing client social media profiles today goes far beyond simple posting. It requires strategy,...

Click Through Rate (CTR): Why it Matters in Digital Marketing

In today’s digital marketing world, data drives decisions. Whether you are running Google Ads,...

Search Everywhere Optimization | Kamlesh Singad

For many years, businesses believed that Search Engine Optimization (SEO) meant only one thing—ranking...

YouTube SEO: The Complete Guide to Rank Videos Higher & Get More Views

YouTube is the second largest search engine in the world, right after Google. Every...

More like this

How to Manage Social Media Profiles Using AI Tools (Posts, Reels & Shorts Complete Guide)

Managing client social media profiles today goes far beyond simple posting. It requires strategy,...

Click Through Rate (CTR): Why it Matters in Digital Marketing

In today’s digital marketing world, data drives decisions. Whether you are running Google Ads,...

Search Everywhere Optimization | Kamlesh Singad

For many years, businesses believed that Search Engine Optimization (SEO) meant only one thing—ranking...