KatInterview

865. Robot Room Cleaner

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to control a robot to clean an entire room, which is represented as a grid. The key challenges are that we don't know the grid's layout, its dimensions, or the robot's starting position. We can only interact with the robot through a limited API: move(), turnLeft(), turnRight(), and clean(). This is a classic exploration problem on an unknown graph, where grid cells are nodes and adjacent empty cells are connected by edges.

Solution

Robot Room Cleaner in Python

# """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
#class Robot:
#    def move(self):
#        """
#        Returns true if the cell in front is open and robot moves into the cell.
#        Returns false if the cell in front is blocked and robot stays in the current cell.
#        :rtype bool
#        """
#
#    def turnLeft(self):
#        """
#        Robot will stay in the same cell after calling turnLeft/turnRight.
#        Each turn will be 90 degrees.
#        :rtype void
#        """
#
#    def turnRight(self):
#        """
#        Robot will stay in the same cell after calling turnLeft/turnRight.
#        Each turn will be 90 degrees.
#        :rtype void
#        """
#
#    def clean(self):
#        """
#        Clean the current cell.
#        :rtype void
#        """

class Solution:
    def cleanRoom(self, robot):
        """
        :type robot: Robot
        :rtype: None
        """
        self.visited = set()
        # Directions: 0: up, 1: right, 2: down, 3: left
        # (row_change, col_change)
        self.directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
        self.robot = robot
        # Start exploration from relative (0,0) facing Up (direction 0)
        self.backtrack(0, 0, 0)

    def go_back(self):
        # Turn 180 degrees
        self.robot.turnRight()
        self.robot.turnRight()
        # Move back
        self.robot.move()
        # Turn 180 degrees again to restore original orientation
        self.robot.turnRight()
        self.robot.turnRight()

    def backtrack(self, row, col, direction):
        # Mark current cell as visited and clean it
        self.visited.add((row, col))
        self.robot.clean()
        
        # Explore all 4 directions
        for _ in range(4):
            # Calculate potential new coordinates
            new_row = row + self.directions[direction][0]
            new_col = col + self.directions[direction][1]
            
            # Check if the cell is unvisited before moving.
            # The `and` operator's short-circuiting is crucial here.
            if (new_row, new_col) not in self.visited and self.robot.move():
                # If move succeeded, recurse
                self.backtrack(new_row, new_col, direction)
                # After recursion, backtrack to the previous cell
                self.go_back()
            
            # Turn right for the next direction
            self.robot.turnRight()
            direction = (direction + 1) % 4

Robot Room Cleaner in Java

/**
 * // This is the robot's control interface.
 * // You should not implement it, or speculate about its implementation
 * interface Robot {
 *     // Returns true if the cell in front is open and robot moves into the cell.
 *     // Returns false if the cell in front is blocked and robot stays in the current cell.
 *     public boolean move();
 *
 *     // Robot will stay in the same cell after calling turnLeft/turnRight.
 *     // Each turn will be 90 degrees.
 *     public void turnLeft();
 *     public void turnRight();
 *
 *     // Clean the current cell.
 *     public void clean();
 * }
 */

class Solution {
    // Directions: 0: up, 1: right, 2: down, 3: left
    // Represents changes in (row, col)
    int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    // Set to store visited cells' coordinates as strings "row,col"
    Set<String> visited = new HashSet<>();
    Robot robot;

    public void cleanRoom(Robot robot) {
        this.robot = robot;
        // Start exploration from relative coordinate (0,0) with initial direction Up (0).
        backtrack(0, 0, 0);
    }

    private void goBack() {
        // Turn 180 degrees
        robot.turnRight();
        robot.turnRight();
        // Move one step forward (which is backward relative to original orientation)
        robot.move();
        // Turn 180 degrees again to restore original orientation
        robot.turnRight();
        robot.turnRight();
    }

    private void backtrack(int row, int col, int dir) {
        // Mark the current cell as visited and clean it.
        String cell = row + "," + col;
        visited.add(cell);
        robot.clean();

        // Explore all 4 directions from the current cell.
        for (int i = 0; i < 4; i++) {
            // Calculate coordinates of the next cell based on current direction.
            int newRow = row + directions[dir][0];
            int newCol = col + directions[dir][1];
            String newCell = newRow + "," + newCol;

            // Try to move to the new cell if it's not visited yet.
            // Short-circuiting of && ensures we check visited before calling move().
            if (!visited.contains(newCell) && robot.move()) {
                // Recursively call backtrack for the new cell.
                // The robot's direction is unchanged.
                backtrack(newRow, newCol, dir);
                // After returning from recursion, move back to the previous cell.
                goBack();
            }
            
            // Turn the robot right for the next iteration.
            robot.turnRight();
            // Update our direction tracker.
            dir = (dir + 1) % 4;
        }
    }
}

Robot Room Cleaner in C++

/**
 * // This is the robot's control interface.
 * // You should not implement it, or speculate about its implementation
 * class Robot {
 *   public:
 *     // Returns true if the cell in front is open and robot moves into the cell.
 *     // Returns false if the cell in front is blocked and robot stays in the current cell.
 *     bool move();
 *
 *     // Robot will stay in the same cell after calling turnLeft/turnRight.
 *     // Each turn will be 90 degrees.
 *     void turnLeft();
 *     void turnRight();
 *
 *     // Clean the current cell.
 *     void clean();
 * };
 */

class Solution {
public:
    // Directions: 0: up, 1: right, 2: down, 3: left
    // Using pair for coordinates (row, col)
    // Up: (-1, 0), Right: (0, 1), Down: (1, 0), Left: (0, -1)
    int directions[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    set<pair<int, int>> visited;

    void cleanRoom(Robot& robot) {
        // Start the exploration from relative coordinate (0,0) with initial direction Up (0).
        backtrack(robot, 0, 0, 0);
    }

private:
    // Helper function to backtrack to the previous cell.
    void goBack(Robot& robot) {
        robot.turnRight();
        robot.turnRight();
        robot.move();
        robot.turnRight();
        robot.turnRight();
    }

    // The main recursive backtracking function.
    void backtrack(Robot& robot, int row, int col, int dir) {
        // Mark the current cell as visited and clean it.
        visited.insert({row, col});
        robot.clean();

        // Explore all 4 directions from the current cell.
        for (int i = 0; i < 4; ++i) {
            // Calculate the coordinates of the next cell in the current direction.
            int newRow = row + directions[dir][0];
            int newCol = col + directions[dir][1];

            // Try to move into the new cell if it hasn't been visited.
            // The short-circuiting of && is important: we check visited before moving.
            if (visited.find({newRow, newCol}) == visited.end() && robot.move()) {
                // If move is successful, recursively explore from the new cell.
                // The direction of the robot remains the same.
                backtrack(robot, newRow, newCol, dir);
                // After recursion returns, backtrack to the previous cell.
                goBack(robot);
            }
            
            // Turn right to face the next direction for the next iteration.
            robot.turnRight();
            // Update our direction tracker.
            dir = (dir + 1) % 4;
        }
    }
};

Robot Room Cleaner in TypeScript

/**
 * class Robot {
 *      // Returns true if the cell in front is open and robot moves into the cell.
 *      // Returns false if the cell in front is blocked and robot stays in the current cell.
 * 		move(): boolean {}
 * 		
 *      // Robot will stay in the same cell after calling turnLeft/turnRight.
 *      // Each turn will be 90 degrees.
 * 		turnRight() {}
 * 		
 *      // Robot will stay in the same cell after calling turnLeft/turnRight.
 *      // Each turn will be 90 degrees.
 * 		turnLeft() {}
 * 		
 * 		// Clean the current cell.
 * 		clean(): {}
 * }
 */

function cleanRoom(robot: Robot): void {
    // Set to store visited cells as strings "row,col"
    const visited: Set<string> = new Set();
    // Directions: 0: up, 1: right, 2: down, 3: left
    // Represents changes in [row, col]
    const directions: number[][] = [[-1, 0], [0, 1], [1, 0], [0, -1]];

    // Helper to move robot back to previous cell and restore orientation
    function goBack(): void {
        robot.turnRight();
        robot.turnRight();
        robot.move();
        robot.turnRight();
        robot.turnRight();
    }

    // Main recursive backtracking function
    function backtrack(row: number, col: number, dir: number): void {
        const cell = `${row},${col}`;
        visited.add(cell);
        robot.clean();

        // Explore all 4 directions
        for (let i = 0; i < 4; i++) {
            const newRow = row + directions[dir][0];
            const newCol = col + directions[dir][1];
            const newCell = `${newRow},${newCol}`;

            // Check visited before moving to prevent unnecessary actions
            if (!visited.has(newCell) && robot.move()) {
                // Recurse into the new cell
                backtrack(newRow, newCol, dir);
                // Backtrack to previous cell after exploration
                goBack();
            }

            // Turn right to try the next direction
            robot.turnRight();
            dir = (dir + 1) % 4;
        }
    }

    // Start from relative (0,0) facing Up (direction 0)
    backtrack(0, 0, 0);
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.