具体是例如下图:
![《剑指offer》:[66]矩阵中的路径](http://p1.codesocang.com/uploads/allimg/c160630/14C2DQL0260-3QH.jpg)
#include <iostream>
using namespace std;
char arr[17]="abcesfcsadeekong";
char strr[6]="bcced";
bool HasPathHelp(char array[],int col,int row,int cols,int rows, char *str,int &pathlength,bool *visited )
{
if(str[pathlength]=='\0')
return true;
bool haspath=false;
if(row>=0 && row<rows && col >=0 && col <cols
&& array[row*cols+col]==str[pathlength]
&& !visited[row*cols+col])
{
++pathlength;
visited[row*cols+col]=true;
haspath=HasPathHelp(array,col-1,row,cols,rows,str,pathlength,visited) //left
|| HasPathHelp(array,col,row-1,cols,rows,str,pathlength,visited) //up
|| HasPathHelp(array,col+1,row,cols,rows,str,pathlength,visited) //right
|| HasPathHelp(array,col,row+1,cols,rows,str,pathlength,visited); //down
if(!haspath)
{
--pathlength;
visited[row*cols+col]=false;
}
}
return haspath;
}
bool HasPath(char array[],int rows, int cols,char *str)
{
if(array==NULL || rows<1 || cols<1 || str==NULL)
return false;
bool *visited=new bool[rows*cols];
memset(visited,0,rows*cols);
int pathlength=0;
for(int row=0;row<rows;row++)
{
for(int col=0;col<cols;col++)
{
if(HasPathHelp(array,col,row,cols,rows,str,pathlength,visited))
return true;
}
}
delete []visited;
return false;
}
int main()
{
bool result=HasPath(arr,4,4,strr);
if(result)
cout<<"该矩阵"<<arr<<"包含"<<strr<<"字符串"<<endl;
else
cout<<"该矩阵"<<arr<<"不包含"<<strr<<"字符串"<<endl;
system("pause");
return 0;
}
运行结果:
![《剑指offer》:[66]矩阵中的路径](http://p1.codesocang.com/uploads/allimg/c160630/14C2DQ950W0-49626.jpg)
热门源码