1041. 困于环中的机器人_中等_模拟

 

 

class Solution {
    /**
     1,初始方向向上 2.一轮指令后,方向可能不变,也可能变 3.方向发生变化,最多四次迭代就能变回初始方向,而且一定能变回初始方向。这点很重要,大家想一想 4.不管是第一轮指定还是第N轮指定以后,第一次达到同方向,看这次的位置是不是(0,0),如果是,则困于循环。如果不是,则不会困住(假设落在(1,1),则再来一轮达到同方向,下次的落点会在 (2,2),下下次会是(3,3),以此类推)
     **/

    public boolean isRobotBounded(String instructions) {
       int []xt = {0,1,0,-1};
       int []yt = {1,0,-1,0};
       int x=0;
       int y=0;
       String str = "";
       for(int i=0;i<4;i++){
           str += instructions;
       }
       int dir = 4000;
       for(int i=0;i<str.length();i++){
           if(str.charAt(i)=='R'){
               dir += 1;
           }
           else if(str.charAt(i)=='L'){
               dir -= 1;
           }
           else if(str.charAt(i)=='G'){
               x += xt[dir%4];
               y += yt[dir%4];
           }
       }
       return x==0&&y==0&&dir%4==0;
    }
}

 

posted @ 2021-09-29 23:12  你的雷哥  阅读(71)  评论(0编辑  收藏  举报