[CareerCup] 9.2 Robot Moving 機器人移動

Grandyang發表於2015-09-17

 

9.2 Imagine a robot sitting on the upper left corner of an X by Y grid. The robot can only move in two directions: right and down. How many possible paths are there for the robot to go from (0,0) to (X,Y)?
 FOLLOW UP
 Imagine certain spots are "off limits," such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.

 

LeetCode上的原題,請參見我之前的部落格Unique Paths 不同的路徑Unique Paths II 不同的路徑之二

 

解法一:

class Solution {
public:
    int getPath(int x, int y) {
        vector<int> dp(y + 1, 1);
        for (int i = 1; i <= x; ++i) {
            for (int j = 1; j <= y; ++j) {
                dp[j] += dp[j - 1];
            }
        }
        return dp[y];
    }
};

 

解法二:

class Solution {
public:
    int getPath(int x, int y) {
        double num = 1, denom = 1;
        int small = x < y ? x : y;
        for (int i = 1; i <= small; ++i) {
            num *= x + y - i + 1;
            denom *= i;
        }
        return (int)(num / denom);
    }
};

 

這道題的Follow up說格子中可能有障礙物,即不能到達的位子,讓我們找到一條從左上點到右下點的路徑,只需一條而已,不用將所有的都找出來,那麼我們使用遞迴來做,我們反方向走,從右下點往左上點找,我們用雜湊表來記錄某個位置是否訪問過,當遞迴到原點的時候,我們把原點加入結果中,然後逐層遞迴返回,把路徑中的點依次加入結果中,這樣結果中儲存的順序就是正確的,參見程式碼如下:

 

class Point {
public:
    int _x, _y;
    Point(int x, int y): _x(x), _y(y) {}
};

class Solution {
public:
    vector<Point*> getPath(vector<vector<int> > &grid, int x, int y) {
        vector<Point*> res;
        unordered_map<Point*, bool> m;
        getPathDFS(grid, x, y, m, res);
        return res;
    }
    bool getPathDFS(vector<vector<int> > &grid, int x, int y, unordered_map<Point*, bool> &m, vector<Point*> &res) {
        if (x < 0 || y < 0 || grid[x][y] == 1) return false;
        Point *p = new Point(x, y);
        if (m.find(p) != m.end()) return m[p];
        bool isAtOrigin = (x == 0) && (y == 0), success = false;
        if (isAtOrigin || getPathDFS(grid, x, y - 1, m, res) || getPathDFS(grid, x - 1, y, m, res)) {
            res.push_back(p);
            success = true;
        }
        m[p] = success;
        return success;
    }
};

 

相關文章