矩陣中的路徑

題目描述

請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如 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;
}




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