1 bool hasPath(char* matrix,int rows,int cols,char* str) 2 { 3 if(matrix==NULL||rows<1||cols<1||str==NULL) 4 return false; 5 bool *visited=new bool[rows*cols]; 6 memset(visited,0,rows*cols); 7 int pathlength=0; 8 for(int row=0;row<rows;++row) 9 { 10 for(int col=0;col<cols;++col) 11 { 12 if(hasPathCore(matrix,rows,cols,row,col,str,pathlength,visited)) 13 { 14 return true; 15 } 16 } 17 } 18 delete[] visited; 19 return false; 20 } 21 22 bool hasPathCore(char* matrix,int rows,int cols,int row,int col,char* str,int& pathlength,bool* visited) 23 { 24 if(str[pathlength]==‘\0‘) 25 return true; 26 bool hasPath=false; 27 if(row>=0&&row<rows&&col>=0&&col<cols28 &&matrix[row*cols+col]==str[pathlength]&&29 !visited[row*cols+col]) 30 { 31 ++pathlength; 32 visited[row*cols+col]=true; 33 34 hasPath=hasPathCore(matrix,rows,cols,row,col-1,str,pathlength,visited)||35 hasPathCore(matrix,rows,cols,row-1,col,str,pathlength,visited)||36 hasPathCore(matrix,rows,cols,row+1,col,str,pathlength,visited)||37 hasPathCore(matrix,rows,cols,row,col+1,str,pathlength,visited); 38 if(!hasPath) 39 { 40 --pathlength; 41 visited[row*cols+col]=false; 42 } 43 } 44 return hasPath; 45 }
原文:http://www.cnblogs.com/wxdjss/p/5478875.html