1
class Solution {
2
public boolean isRobotBounded(String instructions) {
3
if (instructions.length() == 0) {
4
return true;
5
}
6

7
Robot bender = new Robot();
8
int[] start = new int[] {0, 0};
9

10
// 4 represents the max 90 degree turns that can restart initial orientation.
11
for (int i = 0; i < 4; i++) {
12
boolean orientationChanged = bender.performSet(instructions);
13

14
int[] location = bender.location;
15
if (location[0] == start[0] && location[1] == start[1]) {
16
return true;
17
}
18

19
// If robot never turns and the first instruction isn't at start, exit.
20
else if (!orientationChanged) {
21
return false;
22
}
23
}
24

25
return false;
26
}
27
}
28

29
class Robot {
30
int[] location;
31
int[] orientation;
32
int[][] orientations;
33
int orientationPos;
34
boolean orientationChangeCheck;
35

36
Robot() {
37
// Start in center
38
location = new int[] {0, 0};
39

40
// N, E, S, W
41
orientations = new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
42

43
// Start pointing north
44
orientationPos = 0;
45
orientation = orientations[orientationPos];
46

47
// Track if robot has turned
48
orientationChangeCheck = false;
49
}
50

51
public boolean performSet(String orders) {
52
this.orientationChangeCheck = false;
53

54
for (int i = 0; i < orders.length(); i++) {
55
this.perform(orders.charAt(i));
56
}
57

58
return this.orientationChangeCheck;
59
}
60

61
public void perform(char order) {
62
if (order == 'G') {
63
this.go();
64
} else if (order == 'L' || order == 'R') {
65
this.turn(order);
66
} else {
67
// do nothing
68
}
69
}
70

71
public void turn(char direction) {
72
if (direction == 'L') {
73
this.orientationPos = this.orientationPos == 0 ? 3 : this.orientationPos - 1;
74
} else if (direction == 'R') {
75
this.orientationPos = (this.orientationPos + 1) % 4;
76
}
77

78
this.orientation = this.orientations[this.orientationPos];
79
this.orientationChangeCheck = true;
80
}
81

82
public int[] go() {
83
this.location[0] += this.orientation[0];
84
this.location[1] += this.orientation[1];
85
return this.location;
86
}
87
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0