1
+ // Runtime: 2 ms (Top 16.85%) | Memory: 41.9 MB (Top 53.99%)
1
2
class Solution {
2
3
public boolean isRobotBounded (String instructions ) {
3
4
if (instructions .length () == 0 ) {
4
5
return true ;
5
6
}
6
-
7
+
7
8
Robot bender = new Robot ();
8
9
int [] start = new int []{0 , 0 };
9
-
10
- // 4 represents the max 90 degree turns that can restart initial orientation.
10
+
11
+ // 4 represents the max 90 degree turns that can restart initial orientation.
11
12
for (int i = 0 ; i < 4 ; i ++) {
12
13
boolean orientationChanged = bender .performSet (instructions );
13
-
14
+
14
15
int [] location = bender .location ;
15
16
if (location [0 ] == start [0 ] && location [1 ] == start [1 ]) {
16
17
return true ;
17
- }
18
-
19
- // If robot never turns and the first instruction isn't at start, exit.
20
- else if (!orientationChanged ) {
18
+ }
19
+
20
+ // If robot never turns and the first instruction isn't at start, exit.
21
+ else if (!orientationChanged ) {
21
22
return false ;
22
23
}
23
24
}
24
-
25
+
25
26
return false ;
26
27
}
27
28
}
@@ -32,56 +33,56 @@ class Robot {
32
33
int [][] orientations ;
33
34
int orientationPos ;
34
35
boolean orientationChangeCheck ;
35
-
36
+
36
37
Robot () {
37
- // Start in center
38
+ // Start in center
38
39
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
40
+
41
+ // N, E, S, W
42
+ orientations = new int [][]{{1 ,0 }, {0 , 1 }, {-1 , 0 }, {0 , -1 }};
43
+
44
+ // Start pointing north
44
45
orientationPos = 0 ;
45
46
orientation = orientations [orientationPos ];
46
-
47
- // Track if robot has turned
47
+
48
+ // Track if robot has turned
48
49
orientationChangeCheck = false ;
49
50
}
50
-
51
+
51
52
public boolean performSet (String orders ) {
52
53
this .orientationChangeCheck = false ;
53
-
54
+
54
55
for (int i = 0 ; i < orders .length (); i ++) {
55
56
this .perform (orders .charAt (i ));
56
57
}
57
-
58
+
58
59
return this .orientationChangeCheck ;
59
60
}
60
-
61
+
61
62
public void perform (char order ) {
62
63
if (order == 'G' ) {
63
64
this .go ();
64
65
} else if (order == 'L' || order == 'R' ) {
65
66
this .turn (order );
66
67
} else {
67
- // do nothing
68
+ // do nothing
68
69
}
69
70
}
70
-
71
+
71
72
public void turn (char direction ) {
72
73
if (direction == 'L' ) {
73
74
this .orientationPos = this .orientationPos == 0 ? 3 : this .orientationPos - 1 ;
74
75
} else if (direction == 'R' ) {
75
76
this .orientationPos = (this .orientationPos + 1 ) % 4 ;
76
77
}
77
-
78
+
78
79
this .orientation = this .orientations [this .orientationPos ];
79
80
this .orientationChangeCheck = true ;
80
81
}
81
-
82
+
82
83
public int [] go () {
83
84
this .location [0 ] += this .orientation [0 ];
84
85
this .location [1 ] += this .orientation [1 ];
85
86
return this .location ;
86
87
}
87
- }
88
+ }
0 commit comments