59. Spiral Matrix II (Medium)

Description:

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3

Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]


Solution:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        
        result = []
        for i in range(n):
            result.append([0]*n)
            
        shift = {
            (0,1):((1,0),(0,1)),
            (1,0):((0,-1),(3,-1)),
            (0,-1):((-1,0),(1,-1)),
            (-1,0):((0,1),(2,1))
        } 
            
        wall = [-1,n,-1,n] # top bottom left right
        
        row,col = 0,0
        direction = (0,1)
        for i in range(1,n*n+1):
            # print(row,col,i)
            result[row][col] = i
            row += direction[0]
            col += direction[1]
            if row in wall[:2] or col in wall[2:]:
                row -= direction[0]
                col -= direction[1]
                direction,(i,j) = shift[direction]
                row += direction[0]
                col += direction[1]
                wall[i] += j
                
        return result

Performance:

  • Runtime: 36 ms, faster than 86.61% of Python3 online submissions for Spiral Matrix II.
  • Memory Usage: 13.2 MB, less than 30.65% of Python3 online submissions for Spiral Matrix II.
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,878评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,289评论 0 23
  • 如果自己做不到,就不要轻易地许下承诺。 如果你已经许下承诺,那就全力以赴的去付出行动。 一个人,要对自己说出...
    失联的恋爱脑阅读 867评论 1 7
  • 什么时候开始 我的灵魂 逆着人海茫茫 孤独地写着 孤芳自赏的诗章 肉体也虚假歌唱 装出一副 兴致勃勃的模样 混迹于...
    冷墨残韵阅读 229评论 0 1
  • 愿你能有进一步的勇气,亦有退一步的从容。
    欣睿老师阅读 128评论 0 0

友情链接更多精彩内容