leetcode 79 单词搜索

简介

回溯

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;

    }
};
上一篇:06-图1 列出连通集


下一篇:数据结构算法复习3:图相关考点