Sword refers to Offer ------- the path in the matrix

Insert picture description here

Topic link!

Idea: For
this question, we mainly use dfs (of course you can also use bfs), which is a typical search template question. One thing worth noting here is that when I wrote this dfs myself, I liked using a book The array is used to mark which node has passed, but in fact, we don't need it. In dfs, we can change the value of this node to inform that the node has been traversed, and restore the original data when backtracking.

Code:

class Solution {
    
    
public:
    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;
    }
private:
    bool dfs(vector<vector<char>>& b, string& w, int i, int j, int k) {
    
    
        if (i >= b.size() || i < 0 || j >= b[0].size() || j < 0 || b[i][j] != w[k])
            return false;
        if (k == w.length() - 1)
            return true;
        char temp = b[i][j];
        b[i][j] = '/';
        int dx[4] = {
    
    -1, 0, 1, 0}, dy[4] = {
    
    0, 1, 0, -1};
        for (int q = 0; q < 4; q ++ ) {
    
    
            int m = i + dx[q], n = j + dy[q];
            if (dfs(b, w, m, n, k + 1)){
    
    
                b[i][j] = temp;
                return true;
            }
        }
        b[i][j] = temp;
        return false;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/115068399