Cattle off - path matrix

Title Description
Please design a function that determines whether there is a route that contains all the characters of a character string in a matrix. A lattice path may start from any of the matrix, each step in the matrix can be left, right, up, down one grid. If a route that passes through a matrix of a grid, the path can not enter the lattice. For example Here Insert Picture Descriptionthe matrix containing the path "bcced" in a string, but does not contain the matrix "abcb" path, as a character string in the first row of the matrix b occupy the first second after the lattice, can not re-enter the path this grid.
Solution:
1, depth first search
2, define an array of tags VIS, visited position mark
search 3, four directions

class Solution {
public:
    bool DFS(char* matrix, int r, int c, int rows, int cols, char* str, int len, bool* vis)
    {
        if(str[len] == '\0')
            return true;
        if(matrix[r*cols+c]==str[len] && !vis[r*cols+c])
        {
            vis[r*cols+c] = 1;
            return DFS(matrix, r+1, c, rows, cols, str, len+1, vis) || 
                DFS(matrix, r-1, c, rows, cols, str, len+1, vis) || 
                DFS(matrix, r, c+1, rows, cols, str, len+1, vis) ||
                DFS(matrix, r, c-1, rows, cols, str, len+1, vis);
            vis[r*cols+c] = 0;
        }
        return false;
    }
    
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        bool* vis = new bool[rows*cols];
        for(int i=0; i<rows; i++)
            for(int j=0; j<cols; j++)
            {
                memset(vis, 0, rows*cols);
                if(DFS(matrix, i, j, rows, cols, str, 0, vis))
                    return true;
            }
        return false;
    }
};
Published 315 original articles · won praise 119 · views 110 000 +

Guess you like

Origin blog.csdn.net/w144215160044/article/details/105052047