File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 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 )
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments