zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第59题:给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

    题目:
    给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
    思路:
    是第54题的逆向过程
    程序:
    class Solution:
        def generateMatrix(self, n: int) -> List[List[int]]:
            if n <= 0:
                return []
            if n == 1:
                return [[1]]

            matrix = [[0 for i in range(n)] for i in range(n)]

            row_begin = 0
            row_end = n - 1
            column_begin = 0
            column_end = n - 1

            number = 1
            
            while row_begin <= row_end and column_begin <= column_end and number <= n * n:
                for index1 in range(column_begin, column_end + 1):
                    matrix[row_begin][index1] = number
                    number += 1
                row_begin += 1
                for index2 in range(row_begin, row_end + 1):
                    matrix[index2][column_end] = number
                    number += 1
                column_end -= 1
                for index1 in range(column_end, column_begin - 1, -1):
                    if row_end >= row_begin:
                        matrix[row_end][index1] = number
                    number += 1
                row_end -= 1
                for index2 in range(row_end, row_begin - 1, -1):
                    if column_end >= column_begin:
                        matrix[index2][column_begin] = number
                    number += 1
                column_begin += 1
            return matrix  
     
  • 相关阅读:
    linux使用shell执行一个Python文件
    shell编程
    mysql之通过cmd连接远程数据库
    单词辨析
    安全测试
    Linux下使用crontab执行一个shell脚本
    重新梳理Linux系统中Python环境的问题
    selenium 定位元素不稳定怎么解决?
    爬虫数据分析的前景
    Linux下部署python selenium UI自动化测试
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12738611.html
Copyright © 2011-2022 走看看