LeetCode:59. Spiral Matrix II - Python

189 篇文章 3 订阅
151 篇文章 2 订阅

问题描述:

59. 螺旋矩阵 II

给定一个正整数n,生成一个包含 1 n 2 n^2 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入:

3

输出:

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

问题分析:

这个题目和《54. Spiral Matrix》解决方法一样,不同的在于一个是读出来一个是写进去,然后要同步一个计数器即可。

(1)因为从第一个位置开始,顺时针螺旋填写,可理解为,一层一层的填充

(2)所以,就可以一层一层向里处理,依次是,最上层最右层最下层最左层,即这一圈处理完毕,循环进入下一个内圈,直到结束。其中需要注意的时间,最后剩下的可能为一行,或者一列,这时,要单独判断。其中,每次填写一次,就更新一下计数器

(3)需要注意的地方就是,各种边界问题,比较繁琐,要细心即可。

Python3实现:

# @Time   :2018/11/21
# @Author :LiuYinxing


class Solution:
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        if n == 1: return [[1]]

        matrix = [[0] * n for _ in range(n)]

        top = 0  # 上边
        bottom = n - 1  # 下边
        left = 0  # 左边
        right = n - 1  # 右边

        cnt = 1
        while top < bottom and left < right:

            for y in range(left, right + 1):   # 写入最上面一行数据
                matrix[top][y] = cnt
                cnt += 1

            for x in range(top + 1, bottom):  # 写入最右边一列数据
                matrix[x][right] = cnt
                cnt += 1

            for y in range(right, left - 1, -1):  # 写入最下面一行数据
                matrix[bottom][y] = cnt
                cnt += 1

            for x in range(bottom - 1, top, -1):  # 写入最左边一列数据
                matrix[x][left] = cnt
                cnt += 1

            top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1  # 四个边界,分别向内部移动一个位置

        if top == bottom:  # 如果最后剩下一行数据
            for y in range(left, right + 1):
                matrix[top][y] = cnt
                cnt += 1

        elif left == right:  # 如果最后剩下一列数据
            for x in range(top, bottom + 1):
                matrix[x][right] = cnt
                cnt += 1

        return matrix


if __name__ == '__main__':
    matrix = Solution().generateMatrix(6)
    for row in matrix:
        print(row)
     

声明: 总结学习,有问题或不妥之处,可以批评指正哦。

题目链接: leetcode-cn.com/problems/spiral-matrix-ii/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值