解题思路
本题目的思路与54题的思想相似,套用即可。
代码
class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ matrix = [[0]*n for _ in range(n)] rounds = (n+1)//2 t = 1 wide = high = n for i in range(rounds): #轮次逐层计算 for j in range(4): #表示4个边,我们顺时针计算 if j == 0: #表示上边 for z in range(i,wide - i): matrix[i][z] = t t += 1 elif j == 1: #表示右边 for z in range(i + 1,high - i): matrix[z][wide- i -1] = t t += 1 elif j == 2 and high - i -1 != i: #下方 for z in range(wide - i - 2,i-1,-1): matrix[high - i -1][z] = t t += 1 elif j == 3 and wide - i - 1 != i: for z in range(high - i - 2,i,-1): matrix[z][i] = t t += 1 return matrix