classSolution: defgenerateMatrix(self, num: int): # initial list to n x n matrix = [[0]*num for _ inrange(num)] left, right = 0, num-1 top, bottom = 0, num-1 count = 1 while left <= right and top <= bottom: for i inrange(left, right): # left -> right matrix[top][i] = count count +=1 for i inrange(top, bottom): # top -> bottom matrix[i][right] = count count += 1
for i inrange(right, left, -1): # right -> left matrix[bottom][i] = count count += 1 for i inrange(bottom, top, -1): # bottom -> top matrix[i][left] = count count += 1
# update new start point left += 1 right -= 1 top += 1 bottom -= 1 if num % 2 == 1: # 奇數陣列中心需額外處理 mid = num//2 matrix[mid][mid] = count