劍指offer 面試題12 矩陣中的路徑

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

tips: 遍歷矩陣,若矩陣元素等於字符串開頭則繼續搜索下去。
使用回溯。

class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        vector<vector<bool>> visited = vector<vector<bool>>(rows,vector<bool>(cols,false));
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                if(recurseHasPath(matrix,rows,cols,i,j,str,0,visited)) {
                    return true;
                }
            }
        }
        return false;
    }
    bool recurseHasPath(char* matrix,int rows, int cols,int x,int y, char* str,int index,vector<vector<bool>>& visited) {
        if(str[index]=='\0') {
            return true;
        }
        if( x >= 0 && x < rows && y>=0 && y< cols && matrix[x*cols+y]==str[index] && visited[x][y]==false) {
            visited[x][y]=true;
            bool hasPath = recurseHasPath(matrix,rows,cols,x+1,y,str,index+1,visited) || 
                recurseHasPath(matrix,rows,cols,x-1,y,str,index+1,visited) ||
                recurseHasPath(matrix,rows,cols,x,y+1,str,index+1,visited) ||
                recurseHasPath(matrix,rows,cols,x,y-1,str,index+1,visited);
            if(hasPath) {
                return true;
            } else {
                visited[x][y]=false;
            }
        }
        return false;
    }
};
發佈了94 篇原創文章 · 獲贊 10 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章