zoukankan      html  css  js  c++  java
  • 力扣54-螺旋矩阵

    原题 https://leetcode-cn.com/problems/spiral-matrix/submissions/

    给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

    个人理解:把自己比作正在行走的 棋子,按照右,下 ,左,上的顺序进行移动。每一次碰到编辑触发换方向,每一次还方向,走路的行为发生变化,走路的行为就是x,y的坐标。设置好边界和触发边界换向的条件和边界的变化就可以解决这个问题。

    class Solution:
        def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
            if not matrix or not matrix[0]:return []
            M,N = len(matrix),len(matrix[0]) 
            left,right,up,down = 0,N-1,0,M-1 # 边界
            res = [] # 记录走过的路
            x,y = 0,0 # 当前走到的位置
            dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 分别表示移动方向是 右、下、左、上
            cur_d = 0 
            while len(res) != M*N:
                res.append(matrix[x][y])
                if cur_d == 0 and y == right:
                    cur_d += 1
                    up += 1
                elif cur_d == 1 and x == down:
                    cur_d += 1
                    right -= 1
                elif cur_d == 2 and y == left:
                    cur_d += 1
                    down -= 1
                elif cur_d == 3 and x == up:
                    cur_d += 1
                    left += 1
                cur_d %= 4
                x += dirs[cur_d][0]
                y += dirs[cur_d][1]
            return res
    

      

    思路来源

    https://leetcode-cn.com/problems/spiral-matrix/solution/ju-zhen-bian-li-wen-ti-de-si-bu-qu-by-fu-91za/

  • 相关阅读:
    linux下使用tar命令
    ContentType和@ResponseBody
    ActiveMQ两种模式PTP和PUB/SUB<转>
    Postgresql分表与优化
    PostgreSQL存储过程<转>
    PostgreSQL Table Partitioning<转>
    Postgresql查询表的大小
    Postgresql添加/删除触发器示例
    Android TextView 支持的HTML标签
    我只是一直很努力
  • 原文地址:https://www.cnblogs.com/wang102030/p/14539838.html
Copyright © 2011-2022 走看看