海康威视 2022 笔试唯一一道

Leetcode Link: 54. 螺旋矩阵 - 力扣(LeetCode)

题目

解法一: 动态边界法

思路

  1. 初始化上下左右四个边界
  2. 循环,进行➡️⬇️⬅️⬆️遍历,每次遍历后修改边界,边界中没有元素时退出(top>bottomleft>right)

题解

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        if matrix is None: return res
        top,bottom = 0, len(matrix) - 1
        left,right = 0, len(matrix[0]) - 1
        while True:
            for i in range(left,right+1): #➡️
                res.append(matrix[top][i])
            top += 1 
            if top > bottom: break
            for i in range(top,bottom+1): #⬇️
                res.append(matrix[i][right])
            right -= 1
            if right < left: break
            for i in range(right,left-1,-1): #⬅️
                res.append(matrix[bottom][i])
            bottom -= 1
            if bottom < top: break
            for i in range(bottom,top-1,-1): #⬆️
                res.append(matrix[i][left])
            left += 1
            if left > right: break
        return res

启发和联系

螺旋矩阵II