Path in the matrix-depth first traversal

Topic: Path in the matrix

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 certain grid in the matrix, it cannot enter this grid again afterwards.

注意:
	输入的路径不为空;
	所有出现的字符均为大写英文字母;

样例
matrix=
[
  ["A","B","C","E"],
  ["S","F","C","S"],
  ["A","D","E","E"]
]
结果:
str="BCCE" , return "true" 
str="ASAE" , return "false"

Thinking analysis

Problem analysis:
Find a continuous string in the two-dimensional matrix, and each character cannot be reused.
It can be traversed in four directions up, down, left, and right.

Ideas:
1. First traverse the two-dimensional array and find the character with the same first letter as the starting point;
2. From the starting point, move from the four directions up, down, left and right to form a string and match the current string. If the match is successful, Return true, otherwise, continue.
3. Each time before moving from the current point to various directions, set the current character to'\0' to ensure that the current point will not be repeatedly calculated.
4. After returning in the four directions, modify the current value to the original value .

Code


class Solution {
    
    
public:

    bool dfs(vector<vector<char>>& matrix, string &str, int idx, int row, int col) {
    
    
        vector<char> tmp = matrix[0];
        // 越界直接返回false
        if (row < 0 || row >= matrix.size()  || col < 0 || col >= matrix[0].size()) {
    
    
            return false;
        }
        // 当前值与字符串对应的值不匹配,返回false
        if (matrix[row][col] != str[idx]) {
    
    
            return false;
        }
        // 如果字符串全部匹配成功,返回true
        if (idx == str.length() - 1) {
    
    
            return true;
        }
        
        char tmpc = matrix[row][col];
        // 继续遍历之前将当前值修改为'\0',防止重复判断
        matrix[row][col] = '\0';
        // 上下左右四个方向继续搜索。
        if(dfs(matrix, str, idx+1, row - 1, col)) {
    
    
            return true;
        }
        if(dfs(matrix, str, idx+1, row + 1, col)) {
    
    
            return true;
        }
        if (dfs(matrix, str, idx+1, row, col - 1)) {
    
    
            return true;
        }
        if (dfs(matrix, str, idx+1, row, col + 1)) {
    
    
            return true;
        }
        // 计算完成后,还原当前值。
        matrix[row][col] = tmpc;
        return false;
    }
    
    bool hasPath(vector<vector<char>>& matrix, string &str) {
    
    
        for (int i = 0; i < matrix.size(); i++) {
    
    
            for (int j = 0; j < matrix.at(0).size(); j++) {
    
    
                // 找到当前字符串第一个字符相同的位置开始
                if (matrix[i][j] == str[0]) {
    
    
                    bool ret = dfs(matrix, str, 0, i, j);
                    if(ret) {
    
    
                        return ret;
                    }
                }
            }
        }
        return false;
    }
};

If you have any questions or good suggestions and ideas, please comment and leave a message.

Guess you like

Origin blog.csdn.net/PRML_MAN/article/details/114040089