240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 17 | Leetcode 489. Robot Room Cleaner

题解

Hard

BFS

class Solution {
public:
    void cleanRoom(Robot& robot) {
        dfs(robot, 0, 0, 0);
    }

    void goback(Robot &r) {
        r.turnLeft();
        r.turnLeft();
        r.move();
        r.turnRight();
        r.turnRight();
    }

    /*
     * d: new direction in the map
     */
    void dfs(Robot &robot, int i, int j, int d) {
        string pos = to_string(i) + '-' + to_string(j);

        if (visited.count(pos)) {
            return;
        }

        robot.clean();

        visited.insert(pos);

        // 0: 'up', 1: 'right', 2: 'down', 3: 'left'
        for (int k = 0; k < 4; k++, d++) {
            d = d % 4;
            if (robot.move()) {
                dfs(robot, i + dir[d][0], j + dir[d][1], d);
                goback(robot);
            }
            robot.turnRight(); // clockwise motion
        }
    }        

private:
    unordered_set<string> visited;
    int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
};
posted @ 2020-10-02 11:37  CasperWin  阅读(104)  评论(0编辑  收藏  举报