|
| 1 | +# """ |
| 2 | +# This is the robot's control interface. |
| 3 | +# You should not implement it, or speculate about its implementation |
| 4 | +# """ |
| 5 | +# class Robot(object): |
| 6 | +# def move(self): |
| 7 | +# """ |
| 8 | +# Returns true if the cell in front is open and robot moves into the cell. |
| 9 | +# Returns false if the cell in front is blocked and robot stays in the current cell. |
| 10 | +# :rtype bool |
| 11 | +# """ |
| 12 | +# |
| 13 | +# def turnLeft(self): |
| 14 | +# """ |
| 15 | +# Robot will stay in the same cell after calling turnLeft/turnRight. |
| 16 | +# Each turn will be 90 degrees. |
| 17 | +# :rtype void |
| 18 | +# """ |
| 19 | +# |
| 20 | +# def turnRight(self): |
| 21 | +# """ |
| 22 | +# Robot will stay in the same cell after calling turnLeft/turnRight. |
| 23 | +# Each turn will be 90 degrees. |
| 24 | +# :rtype void |
| 25 | +# """ |
| 26 | +# |
| 27 | +# def clean(self): |
| 28 | +# """ |
| 29 | +# Clean the current cell. |
| 30 | +# :rtype void |
| 31 | +# """ |
| 32 | + |
| 33 | +class Solution(object): |
| 34 | + def cleanRoom(self, robot): |
| 35 | + """ |
| 36 | + :type robot: Robot |
| 37 | + :rtype: None |
| 38 | + """ |
| 39 | + # going clockwise : 0: 'up', 1: 'right', 2: 'down', 3: 'left' |
| 40 | + directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] |
| 41 | + visited = set() |
| 42 | + self.backtrack(robot, (0, 0), 0, directions, visited) |
| 43 | + |
| 44 | + def backtrack(self, robot, cell, currentDirection, directions, visited): |
| 45 | + visited.add(cell) |
| 46 | + robot.clean() |
| 47 | + # going clockwise : 0: 'up', 1: 'right', 2: 'down', 3: 'left' |
| 48 | + for i in range(4): |
| 49 | + newDirection = (currentDirection + i) % 4 |
| 50 | + newCell = (cell[0] + directions[newDirection][0], cell[1] + directions[newDirection][1]) |
| 51 | + if not newCell in visited and robot.move(): |
| 52 | + self.backtrack(robot, newCell, newDirection, directions, visited) |
| 53 | + self.goBack(robot) # go back to the previous cell and on the same direction |
| 54 | + # turn the robot following chosen direction : clockwise |
| 55 | + robot.turnRight() |
| 56 | + |
| 57 | + def goBack(self, robot): |
| 58 | + robot.turnRight() |
| 59 | + robot.turnRight() |
| 60 | + robot.move() |
| 61 | + robot.turnRight() |
| 62 | + robot.turnRight() |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
0 commit comments