面试题12:矩阵中的路径
题目:
请设计一个函数,用来判断在一个矩阵中是否在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵的上、下、左、右移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入格子。例如:在下面的3X4的矩阵中包含一条字符串“bfce”的路径。但矩阵中不包含字符串“abfb”的路径,因为字符串的每一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
思路:
给定一个字符串,在一个定义好的矩阵中,可以从任意位置出发,查找有没有给定字符串的路径。假设当前位置的元素ch对应到路径中的第i个字符。如果对应成功,即就是该字符对应路径的第i个字符也正好是ch,接下来去矩阵中的ch字符所在位置的上、下、左、右进行路径中下一个字符的匹配,若不能匹配成功,回溯到上一步,重新进行字符定位。
代码:
bool hasPathCore(const char *matrix,int rows,int cols,int row,int col,
const char *str,int pathLength,bool *visited)
{
if(str[pathLength] == '\0')
{
return true;
}
bool hasPath = false;
if(row >= 0 && row < rows && col >= 0 && col < cols
&& matrix[row*rows+col]==str[pathLength] && !visited[row*cols+col])
// 找到了对应的字符 之前没有被访问过
{
++pathLength;
visited[row*rows+col] = true;//修改访问状态
//去该格子的四周查找下一个字符,是否能在路径内
hasPath = hasPathCore(matrix,rows,cols,row,col-1,str,pathLength,visited)
||hasPathCore(matrix,rows,cols,row-1,col,str,pathLength,visited)
||hasPathCore(matrix,rows,cols,row,col+1,str,pathLength,visited)
||hasPathCore(matrix,rows,cols,row+1,col,str,pathLength,visited);
if(!hasPath)
{
//未查到时,回溯到上一次查找,并修改访问权限
--pathLength;
visited[row*cols+col] = false;
}
}
return hasPath;
}
bool hasPath(char *matrix,int rows,int cols,char *str)
{
if(matrix == NULL || rows < 1 || cols < 1 || str == NULL )
{
return NULL;
}
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(hasPathCore(matrix,rows,cols,row,col,str,pathLength,visited))
{
return true;
}
}
}
return false;
}