劍指offer - 65矩陣中的路徑

題目描述

請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。

思路如下:

以矩陣任意一個格子爲起點,判斷矩陣中的字符和當前字符串的字符是否相等,然後遞歸的向左、右、上、下分別判斷

代碼如下:

class Solution {
public:
bool hasStrPath(char* matrix, int rows, int cols, char* str, int x, int y, bool* flags){
    if(*str == '\0'){ 
        return true;
    }
    if(x < 0 || x >= rows || y < 0 || y >= cols){
        return false;
    }
    if(flags[x*cols+y] == true){
        return false;
    }
    if(*str != matrix[x*cols+y]){
        return false;
    }
    flags[x*cols+y] = true;
    //遞歸求解
    if(hasStrPath(matrix, rows, cols, str+1, x+1, y, flags) ||   
       hasStrPath(matrix, rows, cols, str+1, x-1, y, flags) ||
       hasStrPath(matrix, rows, cols, str+1, x, y+1, flags) ||
       hasStrPath(matrix, rows, cols, str+1, x, y-1, flags)){
        return true;
    }
    //回溯
    flags[x*cols+y] = false;
    return false;
}

bool hasPath(char* matrix, int rows, int cols, char* str)
{
    bool* flags = new bool[rows * cols];
    for(int i = 0; i < rows * cols; i++){
        flags[i] = false;
    }
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            if(hasStrPath(matrix, rows, cols, str, i, j, flags)){
                return true;
            }
        }
    }
    return false;
}

};

 

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