您的位置:首页 > 其它

DFS Word Search

2015-05-10 16:09 169 查看
思想:

DFS

class Solution {
private:
    //Word Search
    int dir[4][2] = {
        { 0,-1},//left
        { 0, 1},//right
        {-1, 0},//top
        { 1, 0},//down
    };
    const int DIR = 4;
    bool rangeOK(vector<vector<char>> &board,int x,int y) {
        const size_t m = board.size();
        const size_t n = board[0].size();
        if(x<0 || x>m-1 || y<0 || y>n-1) return false;
        else return true;
    }
    bool dfs(vector<vector<char>> &board, string word, vector<vector<bool>> &map, int x, int y, int loc) {
        if(loc == word.size()) return true;
        if(!rangeOK(board, x, y)) return false;
        if(map[x][y]) return false;
        if(board[x][y] != word[loc]) return false;
        map[x][y] = true;
        for(int i=0;i<DIR;i++) {
            int xx = x + dir[i][0];
            int yy = y + dir[i][1];
            bool ret = dfs(board, word, map, xx, yy, loc+1);
            if(ret == true) return true;
        }
        map[x][y] = false;
        return false;
    }
public:
    bool exist(vector<vector<char>>& board, string word) {
        const size_t m = board.size();
        const size_t n = board[0].size();
        vector<vector<bool>> map = vector<vector<bool>>(m,vector<bool>(n,false));
        for(int i = 0; i < m; ++i) {
            for(int j = 0; j < n; ++j) {
                if(dfs(board,word,map,i,j,0)) {
                    return true;
                }
            }
        }
        return false;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: