前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >打卡群刷题总结0713——螺旋矩阵 II

打卡群刷题总结0713——螺旋矩阵 II

作者头像
木又AI帮
发布2020-07-16 15:42:11
2760
发布2020-07-16 15:42:11
举报
文章被收录于专栏:木又AI帮木又AI帮

题目:59. 螺旋矩阵 II

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

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 示例: 输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]

解题:

1、按照要求依次添加数字。

代码:

代码语言:javascript
复制
class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        num = n * n
        cur = 1
        matrix = [[0] * n for i in range(n)]
        left, right = 0, n - 1
        top, bottom = 0, n - 1
        while top <= bottom and left <= right:
            for j in range(left, right + 1):
                matrix[top][j] = cur
                cur += 1
            top += 1
            for i in range(top, bottom + 1):
                matrix[i][right] = cur
                cur += 1
            right -= 1
            for j in range(right, left - 1, -1):
                matrix[bottom][j] = cur
                cur += 1
            bottom -= 1
            for i in range(bottom, top - 1, -1):
                matrix[i][left] = cur
                cur += 1
            left += 1
        return matrix
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档