怒刷 LeetCode 100 道 (59)
來自專欄編程人生
題目
Description:
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3Output:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
解法
class Solution: def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ ret = [[0]*n for i in range(n)] t = 1 for i in range((n+1)//2): # circle index for i1 in range(i,n-i-1): ret[i][i1] = t t += 1 for i2 in range(i,n-i-1): ret[i2][n-i-1] = t t += 1 for i3 in range(i,n-i-1): ret[n-i-1][n-i3-1] = t t += 1 for i4 in range(i,n-i-1): ret[n-i4-1][i] = t t += 1 if n%2 != 0: ret[n//2][n//2] = t return ret
推薦閱讀:
※最高效的學習方法——逆向學習法
※20多年編程經驗老手的總結,不可不看
※青華ug網分享線切割編程技巧
※如何把工作做到最好?
※史上最全的數控G代碼編程詳解—你收藏了嗎?