zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    ios风场
    ios avplayer 视频播放器
    iOS 微信支付
    ios 支付宝
    IOS 归档
    ios 友盟统计
    iOS OC部分 NSString
    ios 程序员
    Ios 一个很好用的图片选择器
    mac系统U盘装机 一个被系统坑过的路人
  • 原文地址:https://www.cnblogs.com/mgdzy/p/13440396.html
Copyright © 2011-2022 走看看