Spiral Matrix II - Complete Solution Guide
Spiral Matrix II is LeetCode problem 59, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given a positive integer n , generate an n x n matrix filled with elements from 1 to n 2 in spiral order. Example 1: Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]] Example 2: Input: n = 1 Output: [[1]] Constraints: 1 <= n <= 20
Detailed Explanation
The problem asks us to generate a square matrix of size `n x n` and fill it with numbers from 1 to `n^2` in a spiral order, starting from the top-left corner and moving clockwise. This means filling the first row from left to right, then the last column from top to bottom, then the last row from right to left, and finally the first column from bottom to top. This pattern repeats inwards until the entire matrix is filled.
Solution Approach
The solution simulates the spiral traversal of the matrix. It initializes the matrix with zeros and maintains a current position (row, column) and a current direction. It iterates from 1 to n*n, filling each cell with the current number. After filling a cell, it calculates the next position based on the current direction. If the next position is out of bounds or already filled, it changes the direction to the next direction in the spiral (right -> down -> left -> up) before updating the current position.
Step-by-Step Algorithm
- Step 1: Initialize an n x n matrix with zeros.
- Step 2: Initialize the row (r) and column (c) to 0 (top-left corner).
- Step 3: Initialize the direction to 0 (right). The direction array (dr, dc) contains the row and column increments for each direction.
- Step 4: Iterate from num = 1 to n*n.
- Step 5: Assign the current number 'num' to the current cell matrix[r][c].
- Step 6: Calculate the next row (next_r) and next column (next_c) based on the current direction.
- Step 7: Check if the next cell (next_r, next_c) is within bounds (0 <= next_r < n and 0 <= next_c < n) and if it is empty (matrix[next_r][next_c] == 0).
- Step 8: If the next cell is out of bounds or already filled, change the direction to the next direction in the spiral (direction = (direction + 1) % 4).
- Step 9: Update the current row and column based on the current direction (r += dr[direction], c += dc[direction]).
- Step 10: Repeat steps 5-9 until all cells are filled.
Key Insights
- Insight 1: Simulating the spiral path by defining directions (right, down, left, up) and changing the direction when encountering a boundary or an already filled cell is crucial.
- Insight 2: Using a direction array (dr, dc) to represent the change in row and column indices for each direction simplifies the movement within the matrix.
- Insight 3: Keeping track of the current position (row, column) and updating it based on the current direction is key to the algorithm's success.
Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(n^2)
Topics
This problem involves: Array, Matrix, Simulation.
Companies
Asked at: Adobe, Amazon, Bloomberg, Google, Meta, Microsoft, Roblox, TikTok, Uber, Zoho.