leetcode 1041. 困于环中的机器人

题目地址 : https://leetcode-cn.com/problems/robot-bounded-in-circle/ide

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

"G":直走 1 个单位
"L":左转 90 度
"R":右转 90 度
机器人按顺序执行指令 instructions,并一直重复它们。code

只有在平面中存在环使得机器人永远没法离开时,返回 true。不然,返回 false。blog

示例 1:

输入:"GGLLGG"
输出:true
解释:
机器人从 (0,0) 移动到 (0,2),转 180 度,而后回到 (0,0)。
重复这些指令,机器人将保持在以原点为中心,2 为半径的环中进行移动。
示例 2:

输入:"GG"
输出:false
解释:
机器人无限向北移动。
示例 3:

输入:"GL"
输出:true
解释:
机器人按 (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... 进行移动。
 

提示:

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

 

解答内存

知足不循环的状况只有一种 坐标有变化 最后方向与最开始方向相反,其他都是循环状况ci

 1 class Solution {
 2 public:
 3     const int up = 0;
 4 const int right = 1;
 5 const int down = 2;
 6 const int myleft = 3;
 7 
 8 bool isRobotBounded(string instructions) {
 9     int x = 0; int y = 0; int direct = up;
10     int count = 0;
11     for (int i = 0; i < instructions.size(); i++) {
12         if (instructions[i] == 'G') {
13             if (direct == up) {
14                 y += 1; count++;
15             }
16             else if (direct == down) {
17                 y -= 1; count++;
18             }
19             else if (direct == myleft) {
20                 x -= 1; count++;
21             }
22             else {
23                 x += 1; count++;
24             }
25 
26         }
27         else if (instructions[i] == 'L') {
28             direct = (direct + 4 - 1) % 4;
29 
30         }
31         else if (instructions[i] == 'R') {
32             direct = (direct + 1) % 4;
33         }
34     }
35     if (x == 0 && y == 0)
36         return true;
37     if (direct != up)
38         return true;
39 
40 
41     return false;
42 }
43 };
View Code

 

 

 

 

执行用时 : 4 ms, 在Robot Bounded In Circle的C++提交中击败了96.40% 的用户 内存消耗 : 8.4 MB, 在Robot Bounded In Circle的C++提交中击败了100.00% 的用户leetcode

做者:defddr
连接:https://leetcode-cn.com/problems/two-sum/solution/mo-ni-yu-fa-ti-mu-by-defddr/
来源:力扣(LeetCode)
著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。get

相关文章
相关标签/搜索