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;

    }
};
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14842882.html