golang 解法, 执行用时: 144 ms, 内存消耗: 8.1 MB, 提交时间: 2023-09-04 23:35:16
type Robot struct{
}
var w, h, step int
func Constructor(width int, height int) Robot {
w, h, step = width, height, 0
return Robot{}
}
func (this *Robot) Step(num int) {
// 由于机器人只能走外圈,那么走 (w+h-2)*2 步后会回到起点
// 同时,将 step 取模固定在 [1,(w+h-2)*2] 范围内,这样不需要特判处于原点时的方向
step = (step+num-1)%((w+h-2)*2) + 1
}
func (this *Robot) GetPos() []int {
x, y, _ := get();
return []int{x, y}
}
func (this *Robot) GetDir() string {
_, _, d := get()
return d
}
func get() (x, y int, dir string) {
switch {
case step < w:
return step, 0, "East"
case step < w+h-1:
return w - 1, step - w + 1, "North"
case step < w*2+h-2:
return w*2 + h - 3 - step, h - 1, "West"
default:
return 0, (w+h-2)*2 - step, "South"
}
}
/**
* Your Robot object will be instantiated and called as such:
* obj := Constructor(width, height);
* obj.Step(num);
* param_2 := obj.GetPos();
* param_3 := obj.GetDir();
*/
python3 解法, 执行用时: 220 ms, 内存消耗: 20.4 MB, 提交时间: 2023-09-04 23:28:20
class Robot:
def __init__(self, width: int, height: int):
self.w, self.h, self.s = width, height, 0
def step(self, num: int) -> None:
# 由于机器人只能走外圈,那么走 (w+h-2)*2 步后会回到起点
# 同时,将 s 取模固定在 [1,(w+h-2)*2] 范围内,这样不需要特判处于原点时的方向
self.s = (self.s + num - 1) % ((self.w + self.h - 2) * 2) + 1
def get(self):
s, w, h = self.s, self.w, self.h
if s < w: return s, 0, "East"
if s < w + h - 1: return w - 1, s - w + 1, "North"
if s < w * 2 + h - 2: return w * 2 + h - 3 - s, h - 1, "West"
return 0, (w + h - 2) * 2 - s, "South"
def getPos(self) -> List[int]:
x, y, _ = self.get()
return [x, y]
def getDir(self) -> str:
return self.get()[2]
# Your Robot object will be instantiated and called as such:
# obj = Robot(width, height)
# obj.step(num)
# param_2 = obj.getPos()
# param_3 = obj.getDir()