## @lc app=leetcode id=59 lang=python3## [59] Spiral Matrix II## https://leetcode.com/problems/spiral-matrix-ii/description/## algorithms# Medium (67.47%)# Likes: 6010# Dislikes: 239# Total Accepted: 519.1K# Total Submissions: 740.3K# Testcase Example: '3'## 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#### @lc code=startfromtypingimportListclassSolution:defgenerateMatrix(self,n:int)->List[List[int]]:res=[[0for_inrange(n)]for_inrange(n)]i=1offset=0whilen>0:i=draw(res,n,i,offset)offset+=1n-=2returnresdefdraw(a,n,i,offset):ifn==1:a[offset][offset]=ireturni+1x=y=0d=0for_inrange(4*(n-1)):# print(x, y, i, d)a[offset+x][offset+y]=iifd%4==0:ify<n-1:y+=1else:d+=1x+=1elifd%4==1:ifx<n-1:x+=1else:d+=1y-=1elifd%4==2:ify>0:y-=1else:d+=1x-=1elifd%4==3:ifx>1:x-=1i+=1returni# @lc code=end