简介

回溯

code

class Solution {
public:
    int n;
    int m;
    bool find;
    void dfs(vector<vector<char>>& board, vector<vector<bool>>& visited, string &word, int index, int i, int j){
        if(index == word.size()){
            find = true;
            return;
        }
        if(i >= n) return;
        if(i < 0) return;
        if(j >= m) return;
        if(j < 0) return;
        if(board[i][j] == word[index]){
            if(visited[i][j] == false) {
                visited[i][j] = true;
                dfs(board, visited, word, index+1, i, j+1);
                visited[i][j] = false;

                visited[i][j] = true;
                dfs(board, visited, word, index+1, i, j-1);
                visited[i][j] = false;

                visited[i][j] = true;
                dfs(board, visited, word, index+1, i+1, j);
                visited[i][j] = false;

                visited[i][j] = true;
                dfs(board, visited, word, index+1, i-1, j);
                visited[i][j] = false;
            }
        }else{
            return;
        }
    }
    bool exist(vector<vector<char>>& board, string word) {
        n = board.size();
        m = board[0].size();
        int index = 0;
        vector<vector<bool>> visited(n, vector<bool>(m, false));
        find = false;
        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                dfs(board, visited, word, 0, i, j);
                if(find) return true;
            }
        }
        return false;

    }
};
posted on 2021-06-02 20:50  HDU李少帅  阅读(37)  评论(0编辑  收藏  举报