Spiral Matrix II Solution in Java

Explore More Solutions:

Problem Description

The Spiral Matrix II problem is akin to organizing a chaotic party where everyone wants to dance in a circle, but you only have a limited amount of space. The task is to fill an n x n matrix in a spiral order, starting from the top-left corner and moving to the right, then down, left, and up, until the entire matrix is filled.

Imagine you’re at a buffet, and you want to grab food in a spiral pattern. You start at the first dish, move right to the next, then down to the dessert, left to the drinks, and finally up to the appetizers. By the end, you’ve filled your plate (or matrix) in a delightful spiral!

Code Solution


class Solution {
  public int[][] generateMatrix(int n) {
    int[][] ans = new int[n][n];
    int count = 1;

    for (int mn = 0; mn < n / 2; ++mn) {
      final int mx = n - mn - 1;
      for (int i = mn; i < mx; ++i)
        ans[mn][i] = count++;
      for (int i = mn; i < mx; ++i)
        ans[i][mx] = count++;
      for (int i = mx; i > mn; --i)
        ans[mx][i] = count++;
      for (int i = mx; i > mn; --i)
        ans[i][mn] = count++;
    }

    if (n % 2 == 1)
      ans[n / 2][n / 2] = count;

    return ans;
  }
}

Approach

The approach taken in this solution is quite straightforward. We use a layered approach to fill the matrix. The outermost layer is filled first, followed by the next inner layer, and so on. The process continues until we reach the center of the matrix. If n is odd, we handle the center element separately.

  1. We loop through each layer of the matrix.
  2. For each layer, we fill the top row from left to right, the right column from top to bottom, the bottom row from right to left, and the left column from bottom to top.
  3. We increment our count with each filled position until the matrix is complete.

Time and Space Complexity

Time Complexity: O(n2) – We fill each cell of the matrix exactly once.

Space Complexity: O(n2) – We use an additional matrix of size n x n to store the result.

Real-World Example

Think of a spiral staircase in a fancy hotel. As you walk up, you can see the entire floor below you in a circular view. Similarly, in the Spiral Matrix II problem, we are filling the matrix in a circular manner, layer by layer, just like ascending a spiral staircase.

Similar Problems

If you enjoyed this problem, you might also like these: