• leetcode刷题-59螺旋矩阵2


    题目

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

    思路

    与螺旋矩阵题完全一致

    实现

    class Solution:
        def generateMatrix(self, n: int) -> List[List[int]]:
            result = [[0 for _ in range(n)]for _ in range(n)]
            idx = 1
            left, right, top, bottom = 0, n - 1, 0, n - 1
            while left <= right and top <= bottom:
                for column in range(left, right + 1):
                    result[top][column] = idx 
                    idx += 1
                for row in range(top + 1, bottom + 1):
                    result[row][right] = idx
                    idx += 1
                if left < right and top < bottom:
                    for column in range(right - 1, left, -1):
                        result[bottom][column] = idx
                        idx += 1
                    for row in range(bottom, top, -1):
                        result[row][left] = idx
                        idx += 1
                left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
            return result
  • 相关阅读:
    解决servlet在web.xml中的路径跳转问题
    浅谈上市公司期权
    spring 与mybatis 整合总结
    学习ssm心得
    django中ORM的事务操作
    Celery快速入门
    vagrant 使用指南
    数据库之mysql
    python之pip
    linux基础
  • 原文地址:https://www.cnblogs.com/mgdzy/p/13440396.html
Copyright © 2020-2023  润新知