class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n==0:return []
d=[[0,1],[1,0],[0,-1],[-1,0]]
ans=[[0 for x in range(n)]for y in range(n)]
x=0
y=0
direction=0
num=1
ans[0][0]=num
for i in range(1,n*n):
while(True):
newx=x+d[direction][0]
newy=y+d[direction][1]
if newx>=0 and newx<n and newy>=0 and newy<n and ans[newx][newy]==0:
num+=1
ans[newx][newy]=num
x=newx
y=newy
break
else:
direction=(direction+1)%4
return ans