机器人大冒险----leetcode

18 篇文章 0 订阅
14 篇文章 0 订阅

力扣团队买了一个可编程机器人,机器人初始位置在原点(0, 0)。小伙伴事先给机器人输入一串指令command,机器人就会无限循环这条指令的步骤进行移动。指令有两种:

U: 向y轴正方向移动一格
R: 向x轴正方向移动一格。
不幸的是,在 xy 平面上还有一些障碍物,他们的坐标用obstacles表示。机器人一旦碰到障碍物就会被损毁。

给定终点坐标(x, y),返回机器人能否完好地到达终点。如果能,返回true;否则返回false。

 

示例 1:

输入:command = "URR", obstacles = [], x = 3, y = 2
输出:true
解释:U(0, 1) -> R(1, 1) -> R(2, 1) -> U(2, 2) -> R(3, 2)。
示例 2:

输入:command = "URR", obstacles = [[2, 2]], x = 3, y = 2
输出:false
解释:机器人在到达终点前会碰到(2, 2)的障碍物。
示例 3:

输入:command = "URR", obstacles = [[4, 2]], x = 3, y = 2
输出:true
解释:到达终点后,再碰到障碍物也不影响返回结果。
 

限制:

2 <= command的长度 <= 1000
command由U,R构成,且至少有一个U,至少有一个R
0 <= x <= 1e9, 0 <= y <= 1e9
0 <= obstacles的长度 <= 1000
obstacles[i]不为原点或者终点

AC代码:

class Solution {
    public boolean robot(String command, int[][] obstacles, int x, int y) {
        int now_x=0,now_y=0;
        for(int i=0;i<command.length();i++){
            if(command.charAt(i)=='U')now_y++;
            else if(command.charAt(i)=='R')now_x++;
        }
        int flag=isPassed(command,x,y,now_x,now_y);
        if(flag==-1)return false;
        for(int i=0;i<obstacles.length;i++){
            int cnt=isPassed(command,obstacles[i][0],obstacles[i][1],now_x,now_y);
            if(cnt!=-1&&cnt<flag)return false;
        }
        return true;
    }
    public int isPassed(String command,int x,int y,int now_x,int now_y)
    {
        int round=Math.min(x/now_x,y/now_y);
        int res=round*command.length();
        now_x=now_x*round;
        now_y=now_y*round;
        if(now_x==x&&now_y==y)return res;
        for(int i=0;i<command.length();i++){
            if(command.charAt(i)=='U')now_y++;
            else if(command.charAt(i)=='R')now_x++;
            res++;
            if(now_x==x&&now_y==y)return res;
        }
        return -1;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值