The sword refers to Offer 12. The path in the matrix (DFS + pruning)

Please design a function to determine whether there is a path that contains all the characters of a string in a matrix. The path can start from any grid in the matrix, and each step can move one grid to the left, right, up, and down in the matrix. If a path passes through a grid of the matrix, then the path cannot enter the grid again. For example, the following 3×4 matrix contains a path for the character string "bfce" (the letters in the path are marked in bold).

[[“a”,“b”,“c”,“e”],
[“s”,“f”,“c”,“s”],
[“a”,“d”,“e”,“e”]]

But the matrix does not contain the path of the string "abfb", because after the first character b of the string occupies the second grid in the first row of the matrix, the path cannot enter this grid again.

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D", "E","E"]], word = "ABCCED"
Output: true
Example 2:

Input: board = [["a","b"],["c","d"]], word = "abcd"
Output: false

analysis:

The idea of ​​backtracking discusses the recursion of each node after moving up, down, left, and right 通过对上下左右四个边界和当前元素与当前步数对应的值(board[i][j]与word[k])不同来进行剪枝. code show as below:

class Solution {
    
    
public:
    bool exist(vector<vector<char>>& board, string word) {
    
    
        int m = board.size();
        int n = board[0].size();
        for(int i = 0; i < m; i++){
    
    
            for(int j = 0; j < n; j++){
    
    
                if(dfs(board, word, i, j, 0)) return true;
            }
        }
        return false;
    }
    bool dfs(vector<vector<char>>& board, string word, int i, int j, int k){
    
    
        if(i > board.size() - 1 || i < 0 || j < 0 || j > board[0].size() -1 || 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 + 1, j, k + 1) || 
                   dfs(board, word, i, j - 1, k + 1) || dfs(board, word, i, j + 1, k + 1);
        board[i][j] = word[k]; // 回溯上一步,还原被访问的位置
        return res;

    }
};

Guess you like

Origin blog.csdn.net/qq_34612223/article/details/114324987
Recommended