LeetCode 59: Spiral Matrix II Solution

Master LeetCode problem 59 (Spiral Matrix II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

59. Spiral Matrix II

Problem Explanation

Explanation

To generate a spiral matrix, we can simulate the process of "walking" along the borders of the matrix and filling in the elements. We keep track of the current position and direction of movement. As we move along the borders, we update the matrix with the corresponding values.

Algorithm

  1. Initialize the matrix with all zeros and set the current value to 1.
  2. Define four boundaries: top, bottom, left, and right, which represent the boundaries of the current spiral loop.
  3. Iterate over each value from 1 to n^2, filling the matrix in the spiral order.
  4. Update the current position and direction based on the boundaries.
  5. Return the generated matrix.

Time Complexity

The time complexity of this algorithm is O(n^2) as we visit each cell in the n x n matrix exactly once.

Space Complexity

The space complexity of this algorithm is O(n^2) as we are creating an n x n matrix to store the values.


Solution Code

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

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

            for (int i = top; i <= bottom && value <= n * n; i++) {
                matrix[i][right] = value++;
            }
            right--;

            for (int i = right; i >= left && value <= n * n; i--) {
                matrix[bottom][i] = value++;
            }
            bottom--;

            for (int i = bottom; i >= top && value <= n * n; i--) {
                matrix[i][left] = value++;
            }
            left++;
        }

        return matrix;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 59 (Spiral Matrix II)?

This page provides optimized solutions for LeetCode problem 59 (Spiral Matrix II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 59 (Spiral Matrix II)?

The time complexity for LeetCode 59 (Spiral Matrix II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 59 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 59 in Java, C++, or Python.

Back to LeetCode Solutions