矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 3×4 矩阵
 a     b   c    e 
 s     f    c    s 
  a    d    e    e 
中包含一条字符串 "bcced" 的路径,但是矩阵中不包含 "abcb" 路径,因为字符串的第一个字符 b 占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
解题思路
用回溯法解!
假设矩阵为 matrix,字符串为 str,定义一个与矩阵等大小的 bool 矩阵 isVisited 用于标记格子是否被访问。
1. 当在矩阵 matrix 中找到一个匹配字符串 str 的 index 处字符的格子,标记此格子为已访问。
2. 从该格子开始沿四个方向递归查找下一个格子匹配 str 的 index 处的下一个字符。
1) 若找到,则继续递归匹配下一个字符,以此递归直到匹配到 str 的末尾,或者匹配不到了。
2) 若找不到,则回溯,重新选择下一个和 index 处匹配的格子。
C++ 代码:
bool hasPath(char* matrix, int rows, int cols, char* str, int r, int c, int& index, bool* isVisited) {
    if('\0' == str[index])// 如果到了字符串 str 的末尾, 则表示矩阵中存在一个路径
        return true;
    bool isHasPath = false;
    // 如果座标 <r, c> 处的格子匹配字符串 str 的 index 处的字符,则朝四个方向递归查找下一个匹配的字符
    if(r >= 0 && r < rows && c >= 0 && c < cols &&
            matrix[r*cols+c] == str[index] && !isVisited[r*cols+c]) {
        index++;
        isVisited[r*cols+c] = true;// 标记座标 <r, c> 处的格子为已访问
        isHasPath = hasPath(matrix, rows, cols, str, r, c+1, index, isVisited) ||// 朝右找
                    hasPath(matrix, rows, cols, str, r+1, c, index, isVisited) ||// 朝下找
                    hasPath(matrix, rows, cols, str, r, c-1, index, isVisited) ||// 朝左找
                    hasPath(matrix, rows, cols, str, r-1, c, index, isVisited);// 朝上找
        if(!isHasPath) {// 如果无法找到下一个匹配的格子,则回溯,重新选择和当前字符匹配的格子
            index--;
            isVisited[r*cols+c] = false;
        }
    }
    return isHasPath;
}

bool HasPath(char* matrix, int rows, int cols, char* str) {// 【矩阵中的路径(回溯法解决)】
    if(NULL == matrix || NULL == str || cols <= 0 || cols <= 0)
        return false;
    bool *isVisited = new bool[rows * cols]();// 用来标记格子是否被访问过,初始化全为 0,即 false
    int index = 0;
    for(int r=0; r < rows; r++)
        for(int c=0; c < cols; c++)
            if(hasPath(matrix, rows, cols, str, r, c, index, isVisited)) {
                delete[] isVisited;
                return true;
            }
    delete[] isVisited;
    return false;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章