-
Notifications
You must be signed in to change notification settings - Fork 118
/
1041. Robot Bounded In Circle.cpp
65 lines (60 loc) · 2.17 KB
/
1041. Robot Bounded In Circle.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
62
63
64
65
//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Robot Bounded In Circle.
//Memory Usage: 6.3 MB, less than 19.49% of C++ online submissions for Robot Bounded In Circle.
class Solution {
public:
bool isRobotBounded(string instructions) {
vector<int> pos = {0, 0};
vector<vector<int>> dirs = {{0,1}, {-1,0}, {0,-1}, {1,0}};
int dirId = 0;
for(int i = 0; i < 4; ++i){
for(char c : instructions){
switch(c){
case 'G':
pos[0] += dirs[dirId][0];
pos[1] += dirs[dirId][1];
break;
case 'L':
dirId = (dirId+1)%4;
break;
case 'R':
dirId = (dirId+4-1)%4;
break;
}
}
if(pos[0] == 0 && pos[1] == 0){
return true;
}
}
return false;
}
};
//https://leetcode.com/problems/robot-bounded-in-circle/discuss/290856/JavaC%2B%2BPython-Let-Chopper-Help-Explain
//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Robot Bounded In Circle.
//Memory Usage: 6.2 MB, less than 51.92% of C++ online submissions for Robot Bounded In Circle.
class Solution {
public:
bool isRobotBounded(string instructions) {
vector<int> pos = {0, 0};
vector<vector<int>> dirs = {{0,1}, {-1,0}, {0,-1}, {1,0}};
int dirId = 0;
for(char c : instructions){
switch(c){
case 'G':
pos[0] += dirs[dirId][0];
pos[1] += dirs[dirId][1];
break;
case 'L':
dirId = (dirId+1)%4;
break;
case 'R':
dirId = (dirId+4-1)%4;
break;
}
}
/*if after a sequence of instruction,
the robot doesn't face north,
then it will go to original point after four sequences of instruction
*/
return (pos[0] == 0 && pos[1] == 0) || (dirId != 0);
}
};