Considering the base case (1 * 3) There are several possible choices. 121 212 213 232 312 313 (1 2 3 represents RGB 3 different colors). Then we can consider the next following posible choice in (2 * 3)
Let 121 represents head and tail have the same color and the middle pos varies
Let 123 represent every pos has different color
Then we can derive the following fomular $$b_{121} = a_{121} * 3 + a_{123} * 2$$ $$b_{123} = a_{121} * 2 + a_{123} * 2$$
The trick in this problem is to consider the impossible cases (The robot does not come back to original nor the bot face the initial position after iteration)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { publicbooleanisRobotBounded(String instructions) { int[][] directions = newint[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; intx=0, y = 0; intidx=0; for (char i : instructions.toCharArray()) { if (i == 'L') idx = (idx + 3) % 4; elseif (i == 'R') idx = (idx + 1) % 4; else { x += directions[idx][0]; y += directions[idx][1]; } } return (x == 0 && y == 0) || (idx != 0); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
implSolution { pubfnis_robot_bounded(instructions: String) ->bool { letmut d = (0, 1); letmut p = (0, 0); forcin instructions.chars() { match c { 'G' => p = (p.0 + d.0, p.1 + d.1), 'L' => d = (-d.1, d.0), 'R' => d = (d.1, -d.0), _ => {} } } p == (0, 0) || d != (0, 1) } }