Python编程练习.机器人行走

1.LeetCode974 模拟行走机器人
控制机器人行走的基本思想是:先更新方向变化,再以 步长1 更新坐标。
需要注意的是,原题解中提到:必须注意使用 集合 Set 作为对障碍物使用的数据结构,以便我们可以有效地检查下一步是否受阻。如果不这样做,我们检查障碍点的速度可能会慢大约 10000 倍。

class Solution:
    def robotSim(self, commands, obstacles):
        """
        :type commands: List[int]
        :type obstacles: List[List[int]]
        :rtype: int
        """
        ans=0
        d={'+x':0,'-x':0,'+y':0,'-y':0}
        f={'+x':1,'-x':1,'+y':0,'-y':0}
        obstacleSet = set(map(tuple, obstacles))  #关键步
        direction='+y'
        direction_change={'+y-1':'+x','+y-2':'-x','-y-2':'+x','-y-1':'-x','+x-2':'+y','+x-1':'-y','-x-2':'-y','-x-1':'+y'}
        x=0
        y=0
        for i in commands:
            if i>0:
                for k in range(i):
                    d[direction]+=1
                    coordinate = (d['+x'] - d['-x'], d['+y'] - d['-y'])
                    if coordinate in obstacleSet:
                        d[direction]-=1
                        break
                    
            else:
                direction=direction_change[direction+str(i)]
            ans=max(([d['+x']-d['-x'],d['+y']-d['-y']][0]**2+[d['+x']-d['-x'],d['+y']-d['-y']][1]**2),ans)    
        return(ans)


2.LeetCode62 不同路径
排列组合思想,机器人一共要行走m+n-2步,其中有m-1步要向下,计算下行组合的数量即为不同路径的数量。
 

class Solution:
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        # C^(m-1)_(m+n-2)
        res = 1
        for i in range(m, m+n-1):
            res *= i
            res /= i-m+1
        return int(res)
        #代码源于LeetCode提交记录提交用时最少的范例。

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值