9.8 练手 腾讯50题 59螺旋矩阵2

Leetcode 59. Spiral Matrix II

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 ]
]

想法是先生成一个矩阵之后一个一个往里按顺序往里面填数字,代码如下:

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if n == 1:
            return[[1]]
        output = [[0]*n for _ in range(n)]
        cur = 1
        total = n * n
        left = 0
        right = n
        top = 0
        bottom = n
        while cur <= total:
            for i in range(left, right):
                output[top][i] = cur
                cur += 1
            top += 1
            for i in range(top, bottom):
                output[i][right-1] = cur
                cur += 1
            right -= 1
            for i in range(right-1, left-1, -1):
                output[bottom-1][i] = cur
                cur += 1
            bottom -= 1
            for i in range(bottom-1, top-1, -1):
                output[i][left] = cur
                cur += 1
            left += 1
        return output

beat 54%+

 


需要注意

我发现python在初始化数组的时候,如果使用

output = [[0] * n] * n

会导致得到的

[[0,0,0],
 [0,0,0],
 [0,0,0]]

其实里面的三个数组共享一个地址会一起变化,出了很多bug,可能是python本身变量就是指针的缘故还特别节约资源,之后会看看python核心再重新补一下基础。

 


Discuss 中的解法

1. 用一个turple 控制方向:

class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
    matrix = [[0]*n for _ in range(n)]
    directions = ((0, 1), (1, 0), (0, -1), (-1, 0))
    d = 0
    y, x = 0, 0
    for i in range(1, n*n+1):
        matrix[y][x] = i
        dy, dx = directions[d % 4]
        if -1 < y+dy < n and -1 < x+dx < n and matrix[y+dy][x+dx] == 0:
            y, x = y+dy, x+dx
        else:
            d += 1
            dy, dx = directions[d % 4]
            y, x = y+dy, x+dx
    return matrix

2.各种神奇巧妙:

https://leetcode.com/problems/spiral-matrix-ii/discuss/22282/4-9-lines-Python-solutions

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值