矩陣中的路徑

題目描述

請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串全部字符的路徑。路徑能夠從矩陣中的任意一個格子開始,每一步能夠在矩陣中向左,向右,向上,向下移動一個格子。若是一條路徑通過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如 a b c e s f c s a d e e 矩陣中包含一條字符串"bcced"的路徑,可是矩陣中不包含"abcb"路徑,由於字符串的第一個字符b佔據了矩陣中的第一行第二個格子以後,路徑不能再次進入該格子。
 
思路:
這題和機器人那題相似,只是出發點再也不是(0,0)了,其餘想法相似,代碼以下:
class Solution {
public:
    bool hasFun(char* matrix, int rows, int cols, char* str,int x,int y,bool * flags,int pos)
    {
        if(pos==strlen(str))
        {
            return true;
        }
        if(x>=rows||y>=cols||x<0||y<0)
            return false;
        if(flags[x*cols+y])
            return false;
        if(matrix[x*cols+y]==str[pos])
        {
            flags[x*cols+y]=true;
            bool fc=hasFun(matrix,rows,cols,str,x-1,y,flags,pos+1)||hasFun(matrix,rows,cols,str,x+1,y,flags,pos+1)||hasFun(matrix,rows,cols,str,x,y-1,flags,pos+1)||hasFun(matrix,rows,cols,str,x,y+1,flags,pos+1);
            return fc;
        }
        else
            return false;
    }
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        for(int x=0;x<rows;x++)
        {
            for(int y=0;y<cols;y++)
            {
                if(matrix[x*cols+y]==str[0])
                {
                    bool * flags=new bool[rows*cols];
                    for(int i=0;i<rows*cols;i++)
                    {
                        flags[i]=false;
                    }
                    if(hasFun(matrix,rows,cols,str,x,y,flags,0))
                        return true;
                }
            }
        }
        return false;
    }


};
相關文章
相關標籤/搜索