forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
61 lines (47 loc) · 1.33 KB
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/// Source : https://leetcode.com/problems/robot-bounded-in-circle/
/// Author : liuyubobobo
/// Time : 2019-05-19
#include <iostream>
#include <set>
using namespace std;
/// Just Simulation one instructions sequence
/// If the robot's direction is not still north
/// It can definitely go back!
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
private:
const int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public:
bool isRobotBounded(string instructions) {
int curd = 0;
pair<int, int> cur = make_pair(0, 0);
for(char c: instructions){
if(c == 'G'){
cur.first += d[curd][0];
cur.second += d[curd][1];
}
else if(c == 'L')
curd = (curd + 3) % 4;
else
curd = (curd + 1) % 4;
}
return (!cur.first && !cur.second) || curd;
}
};
int main() {
string ins1 = "RRGRRGLLLRLGGLGLLGRLRLGLRLRRGLGGLLRRRLRLRLLGRGLGRRRGRLG";
cout << Solution().isRobotBounded(ins1) << endl;
// 0
string ins2 = "GGLLGG";
cout << Solution().isRobotBounded(ins2) << endl;
// 1
string ins3 = "GG";
cout << Solution().isRobotBounded(ins3) << endl;
// 0
string ins4 = "GL";
cout << Solution().isRobotBounded(ins4) << endl;
// 1
return 0;
}