题目信息

解题思路

代码

	  class Solution:
	      def generateMatrix(self, n: int) -> List[List[int]]:
	          result = [[-1] * n for _ in range(n)]
	          # dir: 0 right, 1 down, 2 left, 3 up
	          direction = 0
	          x, y = 0, 0
	          for i in range(1, n*n+1):
	              result[x][y] = i
	              if direction == 0:
	                  y += 1
	                  if y >= n or result[x][y] != -1:
	                      y -= 1
	                      direction = 1
	                      x += 1
	              elif direction == 1:
	                  x += 1
	                  if x >= n or result[x][y] != -1:
	                      x -= 1
	                      direction = 2
	                      y -= 1
	              elif direction == 2:
	                  y -= 1
	                  if y < 0 or result[x][y] != -1:
	                      y += 1
	                      direction = 3
	                      x -= 1
	              elif direction == 3:
	                  x -= 1
	                  if x < 0 or result[x][y] != -1:
	                      x += 1
	                      direction = 0
	                      y += 1
	              # print(result)
	          return result
	  ```