Let me explain the flow of this code, which generates an n × n spiral matrix filled with numbers from 1 to n² in a clockwise spiral pattern.
Problem Overview
The goal is to create an n × n matrix where numbers are filled in a spiral order, starting from the top-left corner and moving clockwise. For example, for n = 3, the output should be:
[[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]
Code Flow Explanation
1. Initialization
matrix = [[0]*n for _ in range(n)]
- A matrix of size n × n is initialized with zeros. This matrix will be filled with numbers in spiral order.
top, bottom, left, right = 0, n-1, 0, n-1
num = 1
- Boundaries:
top: The topmost row index (starts at 0).
bottom: The bottommost row index (starts at n-1).
left: The leftmost column index (starts at 0).
right: The rightmost column index (starts at n-1).
- These boundaries define the "walls" of the current spiral layer. As we fill numbers, the boundaries will shrink inward.
num: The current number to be filled into the matrix, starting from 1.
2. Main Loop
while top <= bottom and left <= right:
- The loop continues as long as the boundaries are valid (i.e., the top boundary hasn't crossed the bottom, and the left boundary hasn't crossed the right). This ensures we stop when the entire matrix is filled.
The spiral is filled in four steps for each "layer" of the spiral, moving clockwise:
- Fill the top row (left to right).
- Fill the right column (top to bottom).
- Fill the bottom row (right to left).
- Fill the left column (bottom to top).
After each layer is filled, the boundaries (top, bottom, left, right) are adjusted inward to move to the next inner layer.
3. Step 1: Fill the Top Row (Left to Right)
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
- This loop fills the top row of the current layer, from column
left to column right.
- For each position
matrix[top][i], the current value of num is assigned, and num is incremented.
- After filling the top row,
top is incremented to move the top boundary downward, as this row is now filled.
4. Step 2: Fill the Right Column (Top to Bottom)
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
- This loop fills the rightmost column of the current layer, from row
top to row bottom.
- For each position
matrix[i][right], the current value of num is assigned, and num is incremented.
- After filling the right column,
right is decremented to move the right boundary leftward, as this column is now filled.
5. Step 3: Fill the Bottom Row (Right to Left)
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
- This loop fills the bottom row of the current layer, from column
right to column left, moving backward (hence the step -1 in the range).
- For each position
matrix[bottom][i], the current value of num is assigned, and num is incremented.
- After filling the bottom row,
bottom is decremented to move the bottom boundary upward, as this row is now filled.
6. Step 4: Fill the Left Column (Bottom to Top)
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
- This loop fills the leftmost column of the current layer, from row
bottom to row top, moving upward (hence the step -1 in the range).
- For each position
matrix[i][left], the current value of num is assigned, and num is incremented.
- After filling the left column,
left is incremented to move the left boundary rightward, as this column is now filled.
7. Return the Matrix
return matrix
- Once the loop exits (when
top > bottom or left > right), the entire matrix has been filled in spiral order, and it is returned.
Example Walkthrough (n = 3)
Let's walk through how the matrix is filled for n = 3.
Initial State:
matrix = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
top = 0, bottom = 2, left = 0, right = 2, num = 1
First Layer:
- Fill top row (left to right): Fill row 0, columns 0 to 2.
matrix = [[1, 2, 3],
[0, 0, 0],
[0, 0, 0]]
num = 4, top = 1
- Fill right column (top to bottom): Fill column 2, rows 1 to 2.
matrix = [[1, 2, 3],
[0, 0, 4],
[0, 0, 5]]
num = 6, right = 1
- Fill bottom row (right to left): Fill row 2, columns 1 to 0.
matrix = [[1, 2, 3],
[0, 0, 4],
[0, 6, 5]]
num = 7, bottom = 1
- Fill left column (bottom to top): Fill column 0, rows 1 to 1.
matrix = [[1, 2, 3],
[7, 0, 4],
[0, 6, 5]]
num = 8, left = 1
Second Layer:
Now the boundaries are top = 1, bottom = 1, left = 1, right = 1. We fill the inner 1 × 1 matrix.
- Fill top row (left to right): Fill row 1, column 1.
matrix = [[1, 2, 3],
[7, 8, 4],
[0, 6, 5]]
num = 9, top = 2
- The other steps (right, bottom, left) are skipped because the boundaries have crossed (
top > bottom or left > right).
Final Output:
[[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]
Key Points
- Boundary Management: The boundaries (
top, bottom, left, right) shrink inward after each layer is filled, ensuring we move to the inner spiral.
- Order of Filling: The spiral is filled in a clockwise manner: top row → right column → bottom row → left column.
- Edge Cases: The code handles edge cases like n = 1 (a 1 × 1 matrix) naturally, as the loop will execute only once.
Time and Space Complexity
- Time Complexity: O(n²), as we need to fill all n × n elements in the matrix.
- Space Complexity: O(n²), to store the matrix. The additional variables (
top, bottom, left, right, num) use O(1) space.
This approach is efficient and straightforward for generating a spiral matrix.