forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walking-robot-simulation-ii.py
98 lines (86 loc) · 2.18 KB
/
walking-robot-simulation-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Time: O(1)
# Space: O(1)
class Robot(object):
def __init__(self, width, height):
"""
:type width: int
:type height: int
"""
self.__w = width
self.__h = height
self.__curr = 0
def move(self, num):
"""
:type num: int
:rtype: None
"""
self.__curr += num
def getPos(self):
"""
:rtype: List[int]
"""
n = self.__curr % (2*((self.__w-1)+(self.__h-1)))
if n < self.__w:
return [n, 0]
n -= self.__w-1
if n < self.__h:
return [self.__w-1, n]
n -= self.__h-1
if n < self.__w:
return [(self.__w-1)-n, self.__h-1]
n -= self.__w-1
return [0, (self.__h-1)-n]
def getDir(self):
"""
:rtype: str
"""
n = self.__curr % (2*((self.__w-1)+(self.__h-1)))
if n < self.__w:
return "South" if n == 0 and self.__curr else "East"
n -= self.__w-1
if n < self.__h:
return "North"
n -= self.__h-1
if n < self.__w:
return "West"
n -= self.__w-1
return "South"
# Time: O(1)
# Space: O(1)
class Robot2(object):
def __init__(self, width, height):
"""
:type width: int
:type height: int
"""
self.__w = width
self.__h = height
self.__curr = 0
def move(self, num):
"""
:type num: int
:rtype: None
"""
self.__curr += num
def getPos(self):
"""
:rtype: List[int]
"""
return self.__getPosDir()[0]
def getDir(self):
"""
:rtype: str
"""
return self.__getPosDir()[1]
def __getPosDir(self):
n = self.__curr % (2*((self.__w-1)+(self.__h-1)))
if n < self.__w:
return [[n, 0], "South" if n == 0 and self.__curr else "East"]
n -= self.__w-1
if n < self.__h:
return [[self.__w-1, n], "North"]
n -= self.__h-1
if n < self.__w:
return [[(self.__w-1)-n, self.__h-1], "West"]
n -= self.__w-1
return [[0, (self.__h-1)-n], "South"]