1
+ // https://leetcode.com/problems/robot-bounded-in-circle/
2
+
3
+ /*
4
+ * Breakdown of the for-loop from Leetcode:
5
+ *
6
+ *
7
+
8
+ Now everything is ready to iterate over the instructions.
9
+
10
+ If the current instruction is R, i.e. to turn on the right, the next direction is idx = (idx + 1) % 4.
11
+ Modulo here is needed to deal with the situation - facing west, idx = 3, turn to the right to face north, idx = 0.
12
+
13
+ If the current instruction is L, i.e. to turn on the left, the next direction could written in a
14
+ symmetric way idx = (idx - 1) % 4. That means we have to deal with negative indices. A more simple
15
+ way is to notice that 1 turn to the left = 3 turns to the right: idx = (idx + 3) % 4.
16
+
17
+ If the current instruction is to move, we simply update the coordinates: x += directions[idx][0],
18
+ y += directions[idx][1].
19
+
20
+ *
21
+ *
22
+ */
23
+
24
+ class Solution {
25
+ public boolean isRobotBounded (String instructions ) {
26
+
27
+ /*
28
+ * Time Complexity: O(n) where n = length of instructions
29
+ *
30
+ * Space Complexity: O(n) where n = length of char array, which is based on instructions' length
31
+ */
32
+
33
+ // Create a list of directions
34
+ int dir [][] = {{0 ,1 }, {-1 , 0 }, {0 , -1 }, {1 ,0 }};
35
+ int i = 0 ;
36
+
37
+ // Define initial position
38
+ int x = 0 ;
39
+ int y = 0 ;
40
+
41
+ // Iterate instructions
42
+ for (char c : instructions .toCharArray ()) {
43
+
44
+ if (c == 'L' ){
45
+ i = (i + 1 ) % 4 ;
46
+ }
47
+ else if (c == 'R' ) {
48
+ i = (i + 3 ) % 4 ;
49
+ }
50
+ else {
51
+ x = x + dir [i ][0 ];
52
+ y = y + dir [i ][1 ];
53
+ }
54
+
55
+ }
56
+
57
+ // If either robot changed position or direction, return true. If not, return false
58
+ return x == 0 && y == 0 || i != 0 ;
59
+ }
60
+ }
0 commit comments