The sword refers to the path in the offer acwing 23 matrix (DFS)

Topic

Insert picture description here

answer

DFS search simple question, we take each point of the two-dimensional matrix as a starting point, and then start dfs, as long as one of the conditions is met, it can return true

Code

class Solution {
    
    
public:
    bool dfs(vector<vector<char>> &matrix, string &str, int len, int x, int y) {
    
    
    if (matrix[x][y] != str[len]) return false;
    if (len == str.size() - 1) return true;
    char t = str[len];
    matrix[x][y] = '*';  //标记一个从未出现过的字符
    int dx[4] = {
    
    1, -1, 0, 0};
    int dy[4] = {
    
    0, 0, 1, -1};
    for (int i = 0; i < 4; i++) {
    
    
        int a = x + dx[i], b = y + dy[i];
        if (a >= 0 && a < matrix.size() && b >= 0 && b < matrix[a].size()) {
    
    
            if (dfs(matrix, str, len + 1, a, b)) {
    
    
                return true;
            }
        }
    }
    matrix[x][y] = t;   //还原
    return false;
}

bool hasPath(vector<vector<char>> &matrix, string &str) {
    
    

    for (int i = 0; i < matrix.size(); i++) {
    
    
        for (int j = 0; j < matrix[i].size(); j++) {
    
    
            if (dfs(matrix, str, 0, i, j)) {
    
    
                return true;
            }
        }
    }
    return false;

}
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114987593