leetcode-回溯-79. 单词搜索

 

 

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        int n = board[0].size();
        bool res = false;
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++){
                if(board[i][j] == word[0]){
                    if(back(board, visited,word,i,j,0))  // 对首字母一样的,开始遍历
                        return true;
                }
                    
            }
        return false;
    }

    bool back(vector<vector<char>>& board, vector<vector<bool>> &visited, string word,int i, int j, int index){
        int m = board.size();
        int n = board[0].size();
        if(i>=m||i<0||j>=n||j<0||visited[i][j])
            return false;

        bool res;
        if(board[i][j]!=word[index])
            return false;
        else{
            visited[i][j]=true;
            //cout<<"i: "<<i<<" j: "<<j<<" "<<board[i][j]<<" ====index: "<<index<<endl;
            if(index==word.size()-1)
                return true;
            res = back(board,visited,word,i+1,j,index+1)||back(board,visited,word,i-1,j,index+1)||back(board,visited,word,i,j+1,index+1)||back(board,visited,word,i,j-1,index+1);
            visited[i][j] = false;
        }
        return res;
    }
};

 

posted @ 2021-08-12 20:01  三一一一317  阅读(33)  评论(0)    收藏  举报