On an infinite plane, a robot initially stands at (0, 0)
and faces north. The robot can receive one of three instructions:
"G"
: go straight 1 unit;"L"
: turn 90 degrees to the left;"R"
: turn 90 degrees to the right.
The robot performs the instructions
given in order, and repeats them forever.
Return true
if and only if there exists a circle in the plane such that the robot never leaves the circle.
Example 1:
Input: instructions = "GGLLGG"
Output: true
Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
Example 2:
Input: instructions = "GG"
Output: false
Explanation: The robot moves north indefinitely.
Example 3:
Input: instructions = "GL"
Output: true
Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
Constraints:
1 <= instructions.length <= 100
instructions[i]
is'G'
,'L'
or,'R'
.
這道題說是在一個無限大的區域,有個機器人初始化站在原點 (0, 0) 的位置,面朝北方。該機器人有三種指令可以執行,G表示朝當前方向前進一步,L表示向左轉 90 度,R表示向右轉 90 度,現在給了一些連續的這樣的指令,若一直重復的按順序循環執行下去,問機器人是否會在一個固定的圓圈路徑中循環。首先我們需要執行一遍所有的指令,然后根據最后的狀態(包括位置和朝向)來分析機器人是否之后會一直走循環路線。若執行過一遍所有指令之后機器人還在原點上,則一定是在一個圓圈路徑上(即便是機器人可能就沒移動過,一個點也可以看作是圓圈路徑)。若機器人偏離了起始位置,只要看此時機器人的朝向,只要不是向北,則其最終一定會回到起點,別問博主怎么證明,博主也不知道,大家可以多帶幾個例子試一下。知道了最終狀態和循環路徑的關系,現在就是如何執行這些指令了。也不難,用一個變量表示當前的方向,0表示北,1為東,2為南,3為西,按這個順序寫出偏移量數組 dirs,就是在迷宮遍歷的時候經常用到的那個數組。然后記錄當前位置 cur,初始化為 (0, 0),然后就可以執行指令了,若遇到G指令,根據 idx 從 dirs 數組中取出偏移量加到 cur 上即可。若遇到L指令,idx 是要減1的,為了避免負數,先加上個4,再減1,再對4取余。同理,若遇到R指令,idx 加1之后對4取余。最后判斷若還在原點,或者朝向不為北的時候,返回 true 即可,參見代碼如下:
class Solution {
public:
bool isRobotBounded(string instructions) {
int idx = 0; // 0 north, 1 east, 2 south, 3 west.
vector<int> cur{0, 0};
vector<vector<int>> dirs{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
for (char c : instructions) {
if (c == 'G') {
cur = {cur[0] + dirs[idx][0], cur[1] + dirs[idx][1]};
} else if (c == 'L') {
idx = (idx + 4 - 1) % 4;
} else {
idx = (idx + 1) % 4;
}
}
return (cur[0] == 0 && cur[1] == 0) || idx > 0;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1041
參考資料:
https://leetcode.com/problems/robot-bounded-in-circle/