Given a positive integer n
, generate an n x n
matrix filled with elements from 1
to n^2
in spiral order.
Q: What should be the starting point for the spiral? A: The spiral should start from the top-left corner of the matrix.
Q: Should the numbers be increasing sequentially?
A: Yes, the numbers should start from 1 and increase sequentially up to n^2
.
Q: Is there any constraint on the size of n
?
A: The problem specifies n
as a positive integer, so n
will be at least 1.
n x n
matrix initialized with zeros.top
, bottom
, left
, and right
to control the spiral direction as we fill the matrix.n*n
.def generateMatrix(n):
matrix = [[0] * n for _ in range(n)]
top, bottom, left, right = 0, n - 1, 0, n - 1
num = 1
while top <= bottom and left <= right:
# Fill the top row
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
# Fill the right column
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
# Fill the bottom row
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
# Fill the left column
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
return matrix
n x n
matrix exactly once, so the time complexity is (O(n^2)).n x n
matrix to store the results.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?