标签:
题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中任意一格开始,每一步可以在矩阵中间向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。具体是例如下图:
#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;
}
运行结果:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51788250