//回溯法
/* 32行的 has=f(上)||f(下)||f(左)||f(右); 这个写法比用一个for(1-4)来得简洁明了! */
class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if(matrix==NULL||rows<1||cols<1||str==NULL)return false;
bool *visited=new bool[rows*cols];
memset(visited,0,rows*cols);
int length=0; //str 的长度
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
{
bool h=f(matrix,rows,cols,i,j,str,length,visited);
if(h)return true;
}
delete[]visited;
return false;
}
bool f(char* matrix, int rows, int cols,int row, int col, char* str,int &length,bool *visited)
{
if(str[length]=='\0')return true;
bool has=false;
if(0<=row&&row<rows && 0<=col&&col<cols && str[length]==matrix[row*cols+col] && !visited[row*cols+col])//差点错了!矩阵式一维的!!matrix[row][col] && !visited[row][col])
{
length++;
visited[row*cols+col]=true;
has=f(matrix,rows,cols,row,col-1,str,length,visited)|| //上下左右
f(matrix,rows,cols,row,col+1,str,length,visited)||
f(matrix,rows,cols,row-1,col,str,length,visited)||
f(matrix,rows,cols,row+1,col,str,length,visited);
if(has==false)
{
visited[row*cols+col]=false;
length--;
}
}
return has;
}
};