1.1 题目描述
设计函数判断在一个字符矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵的任意一格开始,每一步可以在矩阵中向上下左右移动一格,且如果一条路径经过了矩阵中的某一格那么该路径不能再次进入该格子。
2 解答
2.1 题目分析
回溯法。
2.2 代码
#include <iostream>
using namespace std;
bool hasPath_m(const char *matrix,int rows, int cols,
int row, int col, const char *str, int sk, bool *vt){
if(!str[sk]) return true;
if(!(-1<row && row<rows && -1<col && col<cols &&
matrix[row*cols+col]==str[sk] && !vt[row*cols+col])) return false;
++sk;
vt[row*cols+col] = true;
if( hasPath_m(matrix,rows,cols,row,col+1,str,sk,vt) ||
hasPath_m(matrix,rows,cols,row+1,col,str,sk,vt) ||
hasPath_m(matrix,rows,cols,row,col-1,str,sk,vt) ||
hasPath_m(matrix,rows,cols,row-1,col,str,sk,vt) ) return true;
vt[row*cols+col] = false;
return false;
}
bool hasPath(const char *matrix,int rows, int cols, const char *str){
if(!matrix || rows<1 || cols<1 || !str) return false;
bool *vt = new bool[rows*cols];
memset(vt,0,rows*cols);
for(int k1(0);k1<rows;++k1)
for(int k2(0);k2<cols;++k2)
if(hasPath_m(matrix,rows,cols,k1,k2,str,0,vt)) return true;
delete[] vt;
return false;
}
int main(){
char sm[] = "abcesfcsadee";
cout << hasPath(sm,4,4,"bcced") << endl;
cout << hasPath(sm,4,4,"abcb") << endl;
return 0;
}