zoukankan      html  css  js  c++  java
  • 【算法题9 螺旋矩阵问题】

    螺旋矩阵1:来源LeetCode54题

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    Example 1:

    Input:
    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]
    

    Example 2:

    Input:
    [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9,10,11,12]
    ]
    Output: [1,2,3,4,8,12,11,10,9,5,6,7]

    class Solution:
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
            return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])

    matrix and [*matrix.pop(0)]是为了防止matrix为空时进行pop出错,and短路机制:matrix为[]时不再执行and后的语句。

    [::-1]每次都要进行旋转

    思路如下路:

    螺旋矩阵2:来源LeetCode59题

    Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    Example:

    Input: 3
    Output:
    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]
    
    class Solution:
        def generateMatrix(self, n):
            """
            :type n: int
            :rtype: List[List[int]]
            """
            A=[[n*n]]
            while A[0][0]>1:
                A=[list(range(A[0][0]-len(A),A[0][0]))]+list(zip(*A[::-1]))
            return A*(n>0)
            

    思路如下:

    其中的A*(n>0)是为了处理n=0的情况。若n=0,返回值为[],若return A则返回[[0]]不符合要求。

  • 相关阅读:
    最小生成数kruskal算法和prim算法
    图的表示及遍历
    mysql忘记root用户密码重置密码的方式
    dwr2.0版本的demo
    web.xml中不同版本的servlet头以及版本控制
    初学jboss
    Filter学习总结,顺便提及点servlet3.0异步filter和异步监听
    监听器
    问题发现和解决
    linux学习
  • 原文地址:https://www.cnblogs.com/yanmk/p/8980173.html
Copyright © 2011-2022 走看看