79. Word Search 深度优先搜索

79. Word Search 深度优先搜索_第1张图片
image.png
class Solution {
public:
    bool exist(vector>& board, string word) {
        if(word.empty() || word.length() == 0){
            return true;
        }
        if(board.size() == 0 || board[0].size() == 0) return false;
        vector> used(board.size(), vector(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> board, vector> &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 深度优先搜索)