回溯法記憶法(矩陣路徑)

 

題目描述

請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如 \begin{bmatrix} a & b & c &e \\ s & f & c & s \\ a & d & e& e\\ \end{bmatrix}\quad⎣⎡​asa​bfd​cce​ese​⎦⎤​  矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。

#include  <iostream>
#include  <vector>
using namespace std;

bool  isPath(char *matrix,vector<char> flags,char* str,int x,int y,int rows,int cols)
{
    if(x<0||y<0||x>rows||y>cols) return false;
    if(matrix[x*cols+y]==*str&&flags.at(x*cols+y)==0){
        flags.at(x*cols+y)=1;
        if(*(str+1)=='\0'){
            return true;
        }
        bool condition=isPath(matrix,flags,(str+1),x,y-1,rows,cols)||
                isPath(matrix,flags,(str+1),x,y+1,rows,cols)||
                isPath(matrix,flags,(str+1),x-1,y,rows,cols)||
                isPath(matrix,flags,(str+1),x+1,y,rows,cols);
        if(condition==false){
            flags.at(x*cols+y)=false;
        }
        return condition;

    }else{
        return false;
    }
}
bool  haspath(char* matrix,int rows,int cols,char *str)
{
    vector<char> flags(rows*cols,0);
    bool condition=false;
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            condition=(condition||isPath(matrix,flags,str,i,j,rows,cols));
        }
    }
    return condition;
}
int main(int argc,char * argv[])
{
    char* str="abcesfcsadee";
    char* str1="abcb";
    bool res=haspath(str,3,4,str1);
    cout<<res;
    return 0;
}

 

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