请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。

[["a","b","c","e"],
["s","f","c","s"],
["a","d","e","e"]]

但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。

示例 1:

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true

示例 2:

输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false

提示:

1 <= board.length <= 200
1 <= board[i].length <= 200

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道深度优先遍历的题目

bool dfs(char** board, int boardSize, int* boardColSize, char* word,int row, int col, int len)
{
    if(word[len] == '\0')
        return true;
	//边界条件
    if( row < 0 || row >= boardSize||
        col < 0 || col >= *boardColSize||
        board[row][col] != word[len])
        return false;    

    char temp = board[row][col];
    board[row][col] = '/';	//遍历过的数据用‘/’划除
	//递归实现深度优先遍历
    bool res =  dfs(board, boardSize, boardColSize, word, row-1, col, len+1)||
                dfs(board, boardSize, boardColSize, word, row, col-1, len+1)||
                dfs(board, boardSize, boardColSize, word, row+1, col, len+1)||
                dfs(board, boardSize, boardColSize, word, row, col+1, len+1);
    
    board[row][col] = temp;
    return res;
}

bool exist(char** board, int boardSize, int* boardColSize, char* word)
{
    for(int i=0;i<boardSize;i++)
    {
        for(int j=0; j<*boardColSize;j++)
        {
            if(dfs(board,boardSize,boardColSize,word,i,j,0))
                return true;
        }
    }
    return false;
}