zoukankan      html  css  js  c++  java
  • NC38 螺旋矩阵

    1. 题目

    给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。

    2. 示例

    输入:[[1,2,3],[4,5,6],[7,8,9]]
    输出:[1,2,3,6,9,8,7,4,5]

    3. 题解

    此题很简单,确认每一圈的边界即可。

    定义四个边界,top,down, left, right。

    然后根据四个边界查找即可。

    4. Code实现

     1 class Solution:
     2     def spiralOrder(self, matrix):
     3         if not matrix:
     4             return []
     5         res = []
     6         m, n = len(matrix), len(matrix[0])
     7         top, down, left, right = 0, m, 0, n
     8         while True:
     9             # top行
    10             for i in range(left, right):
    11                 res.append(matrix[top][i])
    12             top += 1
    13             if top >= down:
    14                 break
    15             # right列
    16             for i in range(top, down):
    17                 # right - 1:右边界是从n开始的
    18                 res.append(matrix[i][right - 1])
    19             right -= 1
    20             if right <= left:
    21                 break
    22             # down行
    23             # right - 1: right列的时候右下角的值已经被取了,因此需要right - 1
    24             for i in range(right - 1, left - 1, -1):
    25                 # down - 1: 因为最后一行取的m
    26                 res.append(matrix[down - 1][i])
    27             # left行
    28             down -= 1
    29             if down <= top:
    30                 break
    31             # down - 1: down行时左下角值被取了,因此需要down - 1
    32             for i in range(down - 1, top - 1, -1):
    33                 res.append(matrix[i][left])
    34             left += 1
    35             if left >= right:
    36                 break
    37         return res
    View Code

    5. 结语

      努力去爱周围的每一个人,付出,不一定有收获,但是不付出就一定没有收获! 给街头卖艺的人零钱,不和深夜还在摆摊的小贩讨价还价。愿我的博客对你有所帮助(*^▽^*)(*^▽^*)!

      如果客官喜欢小生的园子,记得关注小生哟,小生会持续更新(#^.^#)(#^.^#)。

    但行好事 莫问前程
  • 相关阅读:
    动态规划Dynamic Programming: Rod-Cutting Problem
    递归详解,全排列问题
    获取网站根目录Url
    oracle中操作表和权限
    mongo简单封装
    dapper的简单封装
    反射做字段更新日志
    nopcommerce +autofac +owin +webapi
    批处理命令执行程序
    MSMQ的简单使用
  • 原文地址:https://www.cnblogs.com/haifwu/p/15143405.html
Copyright © 2011-2022 走看看