- Medium
- Given a positive integer
n
, generate ann x n
matrix
filled with elements from1
ton2
in spiral order.
We can set the matrix with all zero first. Then we start to walk in the matrix, if the next place is not zero (already visited) or outside the matrix, we turn right.
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
ans=[[0]*n for i in range(n)]
i,j,stepi,stepj=0,0,0,1
for k in range(n*n):
ans[i][j]=k+1
if i+stepi>=n or j+stepj>=n or ans[i+stepi][j+stepj]!=0:
stepi,stepj=stepj,-stepi
i+=stepi
j+=stepj
return ans