# # # @param n int整型 # @return int整型二维数组 # class Solution: def generateMatrix(self , n ): # write code here # write code here if n == 0: a = [] return a dr = [[0, 1], [1, 0], [0, -1], [-1, 0]] nx, ny = 0, 0 x, y = 0, 0 nd = 0 arr = [[0 for i in range(n)] for j in range(n)] for i in range(1, n * n + 1): arr[x][y] = i nx = x + dr[nd][0] ny = y + dr[nd][1] if 0 <= nx < n and 0 <= ny < n and arr[nx][ny] == 0: x = nx y = ny else: nd = (nd + 1) % 4 x = x + dr[nd][0] y = y + dr[nd][1]