Sword refers to Offer 12. Path in matrix (dfs)

Series Article Directory



topic

insert image description here
insert image description here

1. Topic analysis

According to the title, we can know that we need to find a continuous array of strings in the matrix to match words. We can use the deep search method. Of course, it should be noted that each position needs to be searched.

Two, the code

class Solution {
    
    
public:
    bool exist(vector<vector<char>>& board, string word) {
    
    
        row = board.size();        
        col = board[0].size();
        for(int i = 0;i < row;i++)
            for(int j = 0;j < col;j++)
                if(dfs(board,word,i,j,0)) return true; 
        return false;
    }
private:
    int row,col;
    bool dfs(vector<vector<char>>& board, string word,int i,int j,int k){
    
    
        if(i < 0 || i >= row|| j < 0||j >= col|| board[i][j] != word[k]) return false;
        if(k == word.size() - 1) return true;
        board[i][j] = '\0';//走过的路进行标记
        bool res = dfs(board,word,i+1,j,k+1)||dfs(board,word,i,j+1,k+1)
                   ||dfs(board,word,i-1,j,k+1)||dfs(board,word,i,j-1,k+1);//从四个方向进行递归
        board[i][j] = word[k];//递归完进行赋值
        return res;
    }
};

exist: This function is relatively simple, it starts searching from each position, and returns true if one is found.
dfs: search function, the end condition is that the boundary is touched or the current character does not match, it returns false, and
if the last character matches, it returns true.

Summarize

This question mainly tests deep search and backtracking, practice more! ! !

Guess you like

Origin blog.csdn.net/qq_52608074/article/details/127330985