LeetCode第136场周赛

菜鸡我只做出了一道。。。

5055. 困于环中的机器人

在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方。机器人可以接受下列三条指令之一:

  • "G":直走 1 个单位
  • "L":左转 90 度
  • "R":右转 90 度

机器人按顺序执行指令 instructions,并一直重复它们。

只有在平面中存在环使得机器人永远无法离开时,返回 true。否则,返回 false

提示:

  1. 1 <= instructions.length <= 100
  2. instructions[i] 在 {'G', 'L', 'R'} 中

用Java写的,把他给的路径最多跑四次看能否回到原点,能回到原点就能成环 。我瞎猜的结论,结果对了。。看排名靠前的代码没怎么看懂。

 1 class Solution {
 2     public boolean isRobotBounded(String instructions) {
 3         int right = 0,left = 0;
 4         int x = 0,y = 0;
 5         boolean flag = false;
 6         int each = 4;
 7         while(true) {
 8             for (int i =0 ;i<instructions.length();i++)
 9             {
10                 if (instructions.charAt(i) == 'G') {
11                     if((left-right)%4==0)
12                         y++;
13                     else if((left-right)%4==1 || (right-left)%4==3)
14                         x--;
15                     else if((left-right)%4==2 || (right-left)%4==2)
16                         y--;
17                     else if((left-right)%4==3 || (right-left)%4==1)
18                         x++;
19                 } else if (instructions.charAt(i) == 'L') {
20                     left++;
21                 } else if (instructions.charAt(i) == 'R') {
22                     right++;
23                 }
24             }
25             each--;
26          if(x == 0 && y == 0) {
27              flag = true;
28              break;
29          }
30         if(each==0)
31             break;
32         }
33         if(flag) {
34             return true;
35         } else {
36             return false;
37         }
38     }
39 }

猜你喜欢

转载自www.cnblogs.com/Zw1999/p/10851905.html
今日推荐