59. Spiral Matrix II

ArrayMatrixSimulation

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.


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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.