文章出處

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

題目鏈接

class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if(matrix == NULL || str == NULL || rows <= 0 || cols <= 0)
            return false; 
        
        bool *pic = new bool[rows * cols]();
        
        for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < cols; j++)
            {
                if(dfs(matrix, rows, cols, str, pic, i, j))
                {
                    delete [] pic; 
                    return true;
                } 
            }
        }
        
        delete [] pic; 
        return false; 
    }
    
private:
    bool dfs(char* matrix, int rows, int cols, char* str, bool* pic, int i, int j)
    {
        if(*str == '\0')
            return true; 
        
        if(i < 0 || i >= rows || j < 0 || j >= cols)
            return false;
        
        if(pic[i * cols + j] || *str != matrix[i * cols + j])
            return false; 
        
        pic[i * cols + j] = true; 
        bool sign = dfs(matrix, rows, cols, str + 1, pic, i - 1, j) ||
                    dfs(matrix, rows, cols, str + 1, pic, i + 1, j) ||
                    dfs(matrix, rows, cols, str + 1, pic, i, j - 1) ||
                    dfs(matrix, rows, cols, str + 1, pic, i, j + 1); 
        pic[i * cols + j] = false; 
        
        return sign; 
    }


};





文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()