forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRobotBoundedInCircle.java
70 lines (65 loc) · 1.27 KB
/
RobotBoundedInCircle.java
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
66
67
68
69
70
class Solution {
// TC: O(len(instructioons))
// SC: O(1)
private enum Direction {
NORTH,
SOUTH,
WEST,
EAST
}
public boolean isRobotBounded(String instructions) {
int x = 0, y = 0;// starting
Direction direction = Direction.NORTH;
for (char instruction : instructions.toCharArray()) {
if (instruction == 'G') {
switch (direction) {
case NORTH:
y++;
break;
case SOUTH:
y--;
break;
case WEST:
x--;
break;
case EAST:
x++;
break;
}
} else if (instruction == 'L') {
switch (direction) {
case NORTH:
direction = Direction.WEST;
break;
case SOUTH:
direction = Direction.EAST;
break;
case WEST:
direction = Direction.SOUTH;
break;
case EAST:
direction = Direction.NORTH;
break;
}
} else if (instruction == 'R') {
switch (direction) {
case NORTH:
direction = Direction.EAST;
break;
case SOUTH:
direction = Direction.WEST;
break;
case WEST:
direction = Direction.NORTH;
break;
case EAST:
direction = Direction.SOUTH;
break;
}
}
}
if (x == 0 && y == 0) { return true; }
if (direction == Direction.NORTH) { return false; }
return true;
}
}