python leetcode 874. 模拟行走机器人 简单易懂

题目描述

在这里插入图片描述
在这里插入图片描述

解题思路

先假设没有障碍的时候,就使用模拟法即可,主要是注意方向的变换

有障碍时,题目有个坑,即在起点处就有障碍,要特意排除这种情况

查找是否有障碍时,不去遍历所有障碍,而是在这条线上从小到大遍历一遍,看是否存在障碍

代码

class Solution:
    def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
        n=len(commands)
        if n<1:
            return 0
        newobstacles=set([tuple(i) for i in obstacles])#用set存储obstacles
        if (0,0) in newobstacles:#排除起点有障碍的情况,直接去除这个障碍,不影响后续操作
            newobstacles.remove((0,0))
        x,y=0,0
        direction=[(0,1),(1,0),(0,-1),(-1,0)]#上左下右
        curdirection=(0,1)#初始方向向北
        res=0
        for command in commands:
            if command==-1:
                temp=direction.index(curdirection)
                curdirection=direction[(temp+1)%4]#每次向右转,方向就转向下一个状态
            elif command==-2:
                temp=direction[::-1].index(curdirection)
                curdirection=direction[::-1][(temp+1)%4]#向左转则,与上面相反即可
            else:
                newx=x+command*curdirection[0]
                newy=y+command*curdirection[1]#先假设没有障碍时,当前能到达的位置
                if obstacles:
                    if newx==x:#x相等,去y轴从小到大遍历
                        for tempy in range(min(y,newy),max(y,newy)+1):
                            if (x,tempy) in newobstacles:
                                newy=tempy-curdirection[1]#若有障碍,则退回一步,即与原来方向相反的走一步
                                break;
                    else:
                        for tempx in range(min(x,newx),max(x,newx)+1):
                            if (tempx,y) in newobstacles:
                                newx=tempx-curdirection[0]
                                break;
                x,y=newx,newy#每次有新的位置点产生时,计算欧式距离
                res=max(res,x**2+y**2)
        return res
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值