L489. Robot Room Cleaner扫地机器人

class Solution(object):
    def cleanRoom(self, robot):
        """
        :type robot: Robot
        :rtype: None
        """
        self.dfs(robot, 0, 0, 0, 1, set())

    def dfs(self, robot, x, y, direction_x, direction_y, visited):
        robot.clean()
        visited.add((x, y))

        for k in range(4):
            neighbor_x = x + direction_x
            neighbor_y = y + direction_y
            if (neighbor_x, neighbor_y) not in visited and robot.move():
                self.dfs(robot, neighbor_x, neighbor_y, direction_x, direction_y, visited)
                robot.turnLeft() # 扭头
                robot.turnLeft()
                robot.move()     #回原点
                robot.turnLeft()  # 回最初的方向
                robot.turnLeft()
            robot.turnLeft()   #下一个方向, 0,1为上,则 -1,0 为左,其实这里换成right也能通过
            direction_x, direction_y = -direction_y, direction_x

Last updated

Was this helpful?