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/

  • 相关阅读:
    C++ 纸牌 今日头条面试题
    c++ 病句 今日头条面试题
    C++ 球迷 今日头条面试题
    C++ 活动安排
    C++ 弗洛伊德算法
    填坑 bzoj3337
    bzoj3884 上帝与集合的正确用法
    人参中第一次膜你退货
    洛谷P2216 [HAOI2007]理想的正方形
    洛谷 P1099 树网的核+P2491 [SDOI2011]消防
  • 原文地址:https://www.cnblogs.com/wang102030/p/14539838.html
Copyright © 2011-2022 走看看