Skip to content

Commit 87a6cea

Browse files
committed
solve Robot Bounded In Circle
1 parent d9796a6 commit 87a6cea

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
# Time: O(n), One Pass!
3+
# Space: O(1)
4+
#
5+
# After working out some examples, I found that the net direction should not be
6+
# North. Or if it is North, then the robot should be in the same initial point after
7+
# one full cycle.
8+
#
9+
# Extensive mathematical proof required.
10+
# Two proofs required:
11+
# 1. Bounded <=> Cycle. (Cycle => Bounded is trivial)
12+
# 2. Cycle <=> (final directions is not North OR final coordinate is not Origin)
13+
def isRobotBounded(self, instructions: str) -> bool:
14+
coordinate = (0, 0)
15+
direction = (0, 1)
16+
for instruction in instructions:
17+
if instruction == "G":
18+
coordinate = (
19+
coordinate[0] + direction[0],
20+
coordinate[1] + direction[1],
21+
)
22+
elif instruction == "L":
23+
# 0,1 -> -1,0
24+
# -1,0 -> 0,-1
25+
# 0,-1 -> 1,0
26+
# 1,0 -> 0,1
27+
direction = (-1 * direction[1], direction[0])
28+
elif instruction == "R":
29+
# 0,1 -> 1,0
30+
# 1,0 -> 0,-1
31+
# 0,-1 -> -1,0
32+
# -1,0 -> 0,1
33+
direction = (direction[1], -1 * direction[0])
34+
35+
return direction != (0, 1) or coordinate == (0, 0)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import unittest
2+
3+
from robot_bounded_in_circle import Solution
4+
5+
6+
class TestRobotBoundedInCircle(unittest.TestCase):
7+
def test_example_1(self):
8+
assert Solution().isRobotBounded(instructions="GGLLGG") is True
9+
10+
def test_example_2(self):
11+
assert Solution().isRobotBounded(instructions="GG") is False
12+
13+
def test_example_3(self):
14+
assert Solution().isRobotBounded(instructions="GL") is True

0 commit comments

Comments
 (0)