79. Word Search

Insert picture description here

Idea: First find the first word in the table, and then recursively search for the next word.

class Solution {
public:
    int  flag=0;
    int px[4]={0,0,1,-1};
    int py[4]={1,-1,0,0}; 
    bool ans=false;
    bool exist(vector<vector<char>>& board, string word) {
     vector<vector<int> >visit(board.size(),vector<int>(board[0].size(),0));
    for(int i=0;i<board.size();i++){
            for(int j=0;j<board[0].size();j++){
                if(board[i][j]==word[0]&&visit[i][j]==0){
                    visit[i][j]=1;
                    dfs(board,word,visit,1,i,j);
                    if(flag) return ans;
                    visit[i][j]=0;
                }
            }
    }
     return ans;
}
    void dfs(vector<vector<char>>& board,string& word,vector<vector<int>>& visit,int index,int x,int y)   {
        if(index==word.size()){
            ans=true;
            flag=1;
            return;
        }
        for(int i=0;i<4;i++){
            if(x+px[i]<0||x+px[i]>=board.size()||y+py[i]<0||y+py[i]>=board[0].size()) continue;
            if(board[x+px[i]][y+py[i]]==word[index]&&visit[x+px[i]][y+py[i]]==0){
                visit[x+px[i]][y+py[i]]=1;
                if(flag) return;
                dfs(board,word,visit,index+1,x+px[i],y+py[i]);
                //if(flag) return;当初放这里,想想放上面比较好。
                //也可以都写上这个条件。
                visit[x+px[i]][y+py[i]]=0;
            }
        }
    }
};

After reading the solution, you can directly operate on the original array without opening an array to mark it.
In addition, the code is not simple enough.

bool exist(vector<vector<char>>& board, string word) {
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[0].size();j++){
                if(dfs(board,word,i,j,0)){
                    return true;
                }
            }
        }
        return false;
    }
    bool dfs(vector<vector<char>>& board,string& word,int x,int y,int index){
        if(board[x][y]!=word[index]) return false;
        if(index==word.size()-1) return true;
        char tep=board[x][y];
        board[x][y]=0;
        if((x>0&&dfs(board,word,x-1,y,index+1))||
        (y>0&&dfs(board,word,x,y-1,index+1))||
        (x<board.size()-1&&dfs(board,word,x+1,y,index+1))||
        (y<board[0].size()-1&&dfs(board,word,x,y+1,index+1))
        ) {
            return true;
        }
        board[x][y]=tep;
        return false;
    }
Published 161 original articles · Like 68 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/qq_43179428/article/details/105242815