機器人大冒險----leetcode

力扣團隊買了一個可編程機器人,機器人初始位置在原點(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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章