JZX轻语:简

LeetCode 885 - 螺旋矩阵III

发表于2024年05月20日

#模拟

可以通过模拟的方式,使用迭代器的方式计算下一个位置,然后判断该位置是否有效,若有效则加入到结果中,直至结果列表的大小为行 x 列。位置的产生规律不难得知:首先右1步,然后下1步,左2步,上2步,右3步,下3步,左4步,上3步…对于同一个步数,只对应两个方向。我们只需对同一个步数,计算两个方向的逐个位置信息,然后再累加步数,再计算后两个方向的逐个位置信息即可。位置的切换则按右->下->左->上的顺序重复进行。

class Solution:
    # 四个方向的移动差值
    moves = ((0, 1), (1, 0), (0, -1), (-1, 0))

    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
        def get_move():
            step = 1
            cur_direction = 0

            while True:
                # 同一个步数yield两个方向的移动信息
                for i in range(2):
                    for j in range(step): 
                        yield self.moves[cur_direction]
                    cur_direction = (cur_direction + 1) % 4
                step += 1

        move_generator = get_move()
        ans = []
        r, c = rStart, cStart
        while len(ans) < rows * cols:
            if 0 <= r < rows and 0 <= c < cols:
                ans.append([r, c])
            next_move = next(move_generator)
            r, c = r + next_move[0], c + next_move[1]
        return ans

闪念标签:LC

题目链接:https://leetcode.cn/problems/spiral-matrix-iii/