題目: LeetCode - 1041. Robot Bounded In Circle

題目說明

給一個字串,代表機器人移動的指令,機器人會不斷重複這段指令,求機器人的移動範圍是否可以用一個圓圈圍住。

解題思路

若是要滿足題目的條件,則做完一段指令後機器人需要回到原點,或是機器人面向跟最初不同的方向 ( 向北 ),紀錄機器人的座標及面向,並遍歷字串模擬完成指令後的狀態即可。

參考解法

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isRobotBounded(string instructions)
{
pair<int, int> pos, face{0, 1};
for(auto c : instructions)
{
if(c == 'G') pos.first += face.first, pos.second += face.second;
else if(c == 'L') face = {-face.second, face.first};
else face = {face.second, -face.first};
}
return (!pos.first && !pos.second) || face.first || face.second != 1;
}
};