【剑指offer】面试题12 - 矩阵中的路径

面试题12:矩阵中的路径

题目描述:

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用下划线标出)。但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
在这里插入图片描述

链接:LeetCode 牛客网

解法一:DFS + 回溯

class Solution {
    
    
public:
    bool hasPath(string matrix, int rows, int cols, string str) {
    
    
        // write code here
        if(str.size() == 0 || rows <= 0 || cols <= 0 || matrix.size() == 0) return false;
        bool *vis = new bool[rows * cols];
        memset(vis, 0, rows * cols);
        int pathLength = 0;
        for(int i = 0; i < rows; i++)
            for(int j = 0; j < cols; j++)
            {
    
    
                if(DFS(matrix, rows, cols, str, i, j, pathLength, vis))
                {
    
    
                    delete vis;
                    return true;
                }
            }
        delete vis;
        return false;
    }
private:
    bool DFS(string matrix, int rows, int cols, string str, int row, int col, int pathLength, bool *vis)
    {
    
    
        if(str[pathLength] == '\0')
            return true;
        bool hasPath = false;
        if(row >= 0 && col >= 0 && row < rows && col < cols 
           && matrix[cols * row + col] == str[pathLength] 
           && !vis[cols * row + col])
        {
    
    
            pathLength++;
            vis[cols * row + col] = true;
            hasPath = DFS(matrix, rows, cols, str, row, col - 1, pathLength, vis) ||
                      DFS(matrix, rows, cols, str, row, col + 1, pathLength, vis) ||
                      DFS(matrix, rows, cols, str, row - 1, col, pathLength, vis) ||
                      DFS(matrix, rows, cols, str, row + 1, col, pathLength, vis);
            if(!hasPath)
            {
    
    
                pathLength--;
                vis[cols * row + col] = false;
            }
        }
        return hasPath;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45437022/article/details/114368475