美文网首页
79. Word Search 深度优先搜索

79. Word Search 深度优先搜索

作者: 刘小小gogo | 来源:发表于2018-09-23 22:34 被阅读0次
image.png
class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        if(word.empty() || word.length() == 0){
            return true;
        }
        if(board.size() == 0 || board[0].size() == 0) return false;
        vector<vector<bool>> used(board.size(), vector<bool>(board[0].size(), false));
        for(int i = 0; i < board.size(); i++){
            for(int j = 0; j < board[0].size(); j++){
                if(dfs(board, used, word, 0, i, j))
                    return true;
            }
        }
        return false;
    }
private:
    bool dfs(vector<vector<char>> board, vector<vector<bool>> &used,string word, int cur, int x, int y){
        if(cur == word.length()){
            return true;
        }
        if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || used[x][y] || word[cur] != board[x][y]) return false;
        used[x][y] = true;
        bool res = dfs(board, used, word, cur + 1, x+1, y) || 
            dfs(board, used, word, cur + 1, x, y + 1) ||
            dfs(board, used, word, cur + 1, x-1, y) ||
            dfs(board, used, word, cur + 1, x, y - 1);
        used[x][y] = false;
        return res;
    }
};

相关文章

网友评论

      本文标题:79. Word Search 深度优先搜索

      本文链接:https://www.haomeiwen.com/subject/ldoqoftx.html