LeetCode 79. Word Search

Typical dfs questions, written according to the framework. Since I just made 200 and 694 before, dfs is very easy to write. Unlike the first two, dfs needs to return boolean values, so there are slight differences in the code, but the overall structure is the same.

The recursive termination conditions are written at the top.

 

class Solution {
public:
    int di[4]={0,0,1,-1};
    int dj[4]={1,-1,0,0};
    
    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,i,j,word,0)) return true;
            }
        }
        return false;
    }
    
    bool dfs(vector<vector<char>> &board, int i, int j, string &word, int index){if (i<0||i>=board.size()||j<0||j>=board[0].size()||board[i][j]!=word[index]) 
            return false;
        if (index==word.size()-1) return true;
        
        char copy=board[i][j];
        board[i][j] = '#';
        
        bool tmp=false;
        for (int k=0;k<4;++k){
            if (dfs(board,i+di[k],j+dj[k],word,index+1)){
                tmp = true;
                break;
            }
        }
        board[i][j] = copy;
        return tmp;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325227488&siteId=291194637