Robot Room Cleaner

hard backtracking dfs interactive

Problem

A robot in an unknown grid can move(), turnLeft()/turnRight(), and clean(). Cells are 0 (obstacle) or 1 (cell). Clean every reachable cell.

Inputgrid = [[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,0,1,1,1,1],[0,0,0,1,0,0,0,0],[1,1,1,1,1,1,1,1]], start = (1,3)
Outputall reachable cells cleaned
DFS records visited (x,y) in a set; backtrack uses two 180° rotations so the robot ends where it started.

def clean_room(robot):
    DIRS = [(-1,0),(0,1),(1,0),(0,-1)]
    visited = set()
    def dfs(x, y, d):
        robot.clean(); visited.add((x, y))
        for k in range(4):
            nd = (d + k) % 4
            nx, ny = x + DIRS[nd][0], y + DIRS[nd][1]
            if (nx, ny) not in visited and robot.move():
                dfs(nx, ny, nd)
                robot.turnRight(); robot.turnRight(); robot.move()
                robot.turnRight(); robot.turnRight()
            robot.turnRight()
    dfs(0, 0, 0)
function cleanRoom(robot) {
  const DIRS = [[-1,0],[0,1],[1,0],[0,-1]];
  const seen = new Set();
  function dfs(x, y, d) {
    robot.clean(); seen.add(x + "," + y);
    for (let k = 0; k < 4; k++) {
      const nd = (d + k) % 4;
      const nx = x + DIRS[nd][0], ny = y + DIRS[nd][1];
      if (!seen.has(nx + "," + ny) && robot.move()) {
        dfs(nx, ny, nd);
        robot.turnRight(); robot.turnRight(); robot.move();
        robot.turnRight(); robot.turnRight();
      }
      robot.turnRight();
    }
  }
  dfs(0, 0, 0);
}
class Solution {
    int[][] DIRS = {{-1,0},{0,1},{1,0},{0,-1}};
    Set seen = new HashSet<>();
    public void cleanRoom(Robot r) { dfs(r, 0, 0, 0); }
    void dfs(Robot r, int x, int y, int d) {
        r.clean(); seen.add(x + "," + y);
        for (int k = 0; k < 4; k++) {
            int nd = (d + k) % 4, nx = x + DIRS[nd][0], ny = y + DIRS[nd][1];
            if (!seen.contains(nx + "," + ny) && r.move()) {
                dfs(r, nx, ny, nd);
                r.turnRight(); r.turnRight(); r.move();
                r.turnRight(); r.turnRight();
            }
            r.turnRight();
        }
    }
}
void dfs(Robot& r, int x, int y, int d, set>& seen, vector>& DIRS) {
    r.clean(); seen.insert({x, y});
    for (int k = 0; k < 4; k++) {
        int nd = (d + k) % 4, nx = x + DIRS[nd].first, ny = y + DIRS[nd].second;
        if (!seen.count({nx, ny}) && r.move()) {
            dfs(r, nx, ny, nd, seen, DIRS);
            r.turnRight(); r.turnRight(); r.move();
            r.turnRight(); r.turnRight();
        }
        r.turnRight();
    }
}
void cleanRoom(Robot& r) {
    vector> DIRS = {{-1,0},{0,1},{1,0},{0,-1}};
    set> seen;
    dfs(r, 0, 0, 0, seen, DIRS);
}
Time: O(N − M) Space: O(N − M)