劍指offer. 12 矩陣中的路徑

劍指offer. 12 矩陣中的路徑

題目描述:

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

解題思路:

dfs

代碼:

//
class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if(matrix == nullptr || rows<=0 || cols <= 0 ||str == nullptr)
            return false;
        bool *visited = new bool[rows*cols](); 
        int pathlength = 0;
        for(int i=0;i<rows;++i){
            for(int j = 0;j<cols;++j){
                if(hasPathCore(matrix,rows,cols,i,j,pathlength,str,visited))
                    return true;
            }
        }
        
        delete[] visited;
        return false;
    }
    
    bool hasPathCore(char *matrix,int rows,int cols,int cur_r,int cur_c,int &length,char * str,bool *visited){

        if(str[length] == '\0')
            return true;
        if(cur_r >= rows || cur_c >= cols || cur_r<0 || cur_c<0)
            return false;
        int cur = cur_r*cols+cur_c;
        bool res = 0;
        if( matrix[cur] == str[length] && visited[cur]== 0){ 
            visited[cur] = 1;
            ++length;
            res = hasPathCore(matrix,rows,cols,cur_r+1,cur_c,length,str,visited) ||
            hasPathCore(matrix,rows,cols,cur_r-1,cur_c,length,str,visited)||
            hasPathCore(matrix,rows,cols,cur_r,cur_c-1,length,str,visited) ||
            hasPathCore(matrix,rows,cols,cur_r,cur_c+1,length,str,visited);
            
            if(!res){
                --length;
                visited[cur] = 0;
            }
        }
        
        return res;
            
    }
};

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