zoukankan      html  css  js  c++  java
  • leetcode_59. 螺旋矩阵 II

    给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
    
     
    
    示例 1:
    
    
    输入:n = 3
    输出:[[1,2,3],[8,9,4],[7,6,5]]
    示例 2:
    
    输入:n = 1
    输出:[[1]]
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/spiral-matrix-ii
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    class Solution:
        def generateMatrix(self, n: int) -> List[List[int]]:
            if n==0:return [[]]
            if n==1 :return [[1]]
            res=[[0]*n for _ in range(n)]
            directions=[[0,1],[1,0],[0,-1],[-1,0]]
            i=1
            directionIndex=0
            row,column=0,0
            while(i<=n*n):
                res[row][column]=i
                nextRow,nextColumn=row+directions[directionIndex][0],column+directions[directionIndex][1]
                if not(0<=nextRow<n and 0<=nextColumn<n and res[nextRow][nextColumn]==0):
                    directionIndex=(directionIndex+1)%4
                row+=directions[directionIndex][0]
                column+=directions[directionIndex][1]
                i+=1
            return res
    
  • 相关阅读:
    五种I/O模型
    Python socket服务
    Python 协程
    python openpyxl 简单使用
    python 文件夹压缩
    Python 多进程
    MySQL 自定义函数
    python 队列
    python 多线程、线程锁、事件
    python paramiko模块:远程连接服务器
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14409134.html
Copyright © 2011-2022 走看看