Leetcode 885. Spiral Matrix III解题报告(python)

885. Spiral Matrix III

  1. Spiral Matrix III python solution

题目描述

On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east.
Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the grid is at the last row and column.
Now, we walk in a clockwise spiral shape to visit every position in this grid.
Whenever we would move outside the boundary of the grid, we continue our walk outside the grid (but may return to the grid boundary later.)
Eventually, we reach all R * C spaces of the grid.
Return a list of coordinates representing the positions of the grid in the order they were visited.

在这里插入图片描述

解析

解题思路也比较简单,只需要顺时针行走,检查目前的位置是否在grid内,如果在范围内就存下。

// An highlighted block
class Solution:
    def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
        totalItems = R*C
        step = 0
        x,y = r0, c0
        res = [[x, y]]
        while len(res)<R*C:
            step += 1
            x, y, res = self.moveRight(x, y, step, res, R, C)
            x, y, res = self.moveDown(x,y, step, res, R, C)
            step += 1
            x, y, res = self.moveLeft(x, y, step, res, R, C)
            x, y, res = self.moveUp(x, y, step, res, R, C)
        
        return res
    
    def moveRight(self, x, y, step, res, R, C):
        while step > 0:
            step -= 1
            y += 1
            if 0<=x<R and 0<=y<C:
                res.append([x,y])
        
        return x, y, res
        
    def moveDown(self, x, y, step, res, R, C):
        while step > 0:
            step -= 1
            x += 1
            if 0<=x<R and 0<=y<C:
                res.append([x,y])

        return x, y, res
    
    def moveLeft(self, x, y, step, res, R, C):
        while step > 0:
            step -= 1
            y -= 1
            if 0<=x<R and 0<=y<C:
                res.append([x,y])
        

Reference

https://leetcode.com/problems/spiral-matrix-iii/discuss/411199/Python-Solution-very-clean

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值