PINEAL.ME   Archives  About

Depth first search in matrix

Robot Room Cleaner

Given a robot cleaner in a room modeled as a grid.

Each cell in the grid can be empty or blocked.

The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees.

When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell.

Design an algorithm to clean the entire room using only the 4 given APIs shown below.

interface Robot {
  // returns true if next cell is open and robot moves into the cell.
  // returns false if next cell is obstacle and robot stays on the current cell.
  boolean move();

  // Robot will stay on the same cell after calling turnLeft/turnRight.
  // Each turn will be 90 degrees.
  void turnLeft();
  void turnRight();

  // Clean the current cell.
  void clean();
}

reference: Leetcode

/**
 * // 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:
    int x = 0;
    int y = 0;
    int dir = 0;
    
    unordered_set<string> cleaned;
    int dx[4]={0, -1, 0, 1};    //define it anti-clockwisely
    int dy[4]={1, 0, -1, 0};    //N -> W -> S -> E
    
    void turnAround(Robot & r) {
        r.turnRight();
        r.turnRight();
    }
    
    void cleanRoom(Robot& robot) {
        string state = to_string(x) + " " + to_string(y);
        if (cleaned.count(state)) {
            return;
        }    
        
        cleaned.emplace(state);        
        robot.clean();
    
        //try 
        for (int i = 0; i < 4; i++) {
            if (robot.move()) {
                //record the current location
                x += dx[dir];
                y += dy[dir];
                //dfs goto next state
                cleanRoom(robot);
                //reset old location
                turnAround(robot);
                robot.move();
                x -= dx[dir];
                y -= dy[dir];                
                //reset old direction 
                turnAround(robot);
            }
            //make turn anti-clockwisely 
            // - we are going to try next direction 
            robot.turnLeft();
            //record the current direction
            dir = (dir + 1) % 4;
        }
    }
};

Generate Random Maze

Question

Randomly generate a maze of size N * N (where N = 2K + 1) whose corridor and wall’s width are both 1 cell. For each pair of cells on the corridor, there must exist one and only one path between them. (Randomly means that the solution is generated randomly, and whenever the program is executed, the solution can be different.). The wall is denoted by 1 in the matrix and corridor is denoted by 0.

Assumptions

N = 2K + 1 and K >= 0 the top left corner must be corridor there should be as many corridor cells as possible for each pair of cells on the corridor, there must exist one and only one path between them

Examples

N = 5, one possible maze generated is

    0  0  0  1  0

    1  1  0  1  0

    0  1  0  0  0

    0  1  1  1  0

    0  0  0  0  0

Solution

void dfs(vector<vector<int>> & res, int x, int y) {
    int n = res.size();
    vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    random_shuffle(dirs.begin(), dirs.end());
    int xx, xxx, yy, yyy;
    xx = xxx = x;
    yy = yyy = y;
    for (const auto & dir : dirs) {
        int dx =dir.first;
        int dy = dir.second;
        xx = x + dx;
        xxx = x + dx * 2;
        yy = y + dy;
        yyy = y + dy * 2;

        if (xxx >= 0 && xxx < n && yyy >= 0 && yyy < n && res[xxx][yyy] != 0) {
            res[xxx][yyy] = 0;
            res[xx][yy] = 0;
            dfs(res, xxx, yyy);
        }
    }
}

vector<vector<int> > generateRandomMaze(int n) {
    vector<vector<int>> res(n, vector<int>(n, 1));
    dfs(res, 0, 0);
    return res;
}
DFS