题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵任意一格开始,每一步可以在矩阵中向上下左右移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如在下面的3*4矩阵中包含一条字符串‘`bcced',的路径(路径中的字母用斜体表示)。但矩阵中不包含字符串“abcd”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
a b c e
s f c s
a d e e
自己的解题代码,主要部分就一个递归的函数,十行不到:
#include <iostream>
#include <new>
#include <string>
class findpath{
private:
char* Matrix;
char* target_string;
bool* had_searched;
unsigned int W;
unsigned int H;
bool string_had_find;
void recursion(unsigned int col, unsigned int row, unsigned int depth);
public:
findpath(){
init_W_and_H();
init_Matrix();
};
~findpath(){
delete[] Matrix;
delete[] had_searched;
}
void init_W_and_H();
void init_Matrix();
void set_had_searched(unsigned int col, unsigned int row);
void unset_had_searched(unsigned int col, unsigned int row);
bool is_searched(unsigned int col, unsigned int row);
void get_target_string();
bool find_string();
};
void findpath::init_W_and_H()
{
using namespace std;
cout << "please input w and H:" << endl<<"W = ";
cin >> W;
cout << "H = ";
cin >> H;
if (W <= 0 || H <= 0)
init_W_and_H();
}
void findpath::init_Matrix()
{
Matrix = new char[W*H];
if (Matrix == NULL){
std::cout << "alloc Matrix error!" << std::endl;
exit(1);
}
had_searched = new bool[W*H]{false};
if (had_searched == NULL){
std::cout << stderr << "alloc had_searched error!"<<std::endl;
exit(1);
}
std::cout<<"please input the member of matrix:";
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++)
std::cin >> Matrix[i*W + j];
}
bool findpath::is_searched(unsigned int col, unsigned int row)
{
return had_searched[row*W + col] == true;
}
void findpath::recursion(unsigned int col, unsigned int row, unsigned int depth)
{
if (col<0 || col>W || row<0 || row>H || depth > (strlen(target_string) - 1)||is_searched(col, row))
return;
set_had_searched(col, row);
if (Matrix[row*W + col] == target_string[depth]){
if (depth == (strlen(target_string) - 1))
string_had_find = true;
recursion(col, row-1, depth + 1);
recursion(col, row+1, depth + 1);
recursion(col-1, row, depth + 1);
recursion(col+1, row, depth + 1);
}
unset_had_searched(col, row);
}
void findpath::set_had_searched(unsigned int col, unsigned int row)
{
had_searched[row*W + H] = true;
}
void findpath::unset_had_searched(unsigned int col, unsigned int row)
{
had_searched[row*W + H] = false;
}
void findpath::get_target_string()
{
std::cout << "input target string :";
target_string = new char[W*H];
std::cin >> target_string;
string_had_find = false;
}
bool findpath::find_string()
{
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++){
recursion(j, i, 0);
if (string_had_find == true)
return true;
}
return false;
}
int main()
{
findpath matrix;
matrix.get_target_string();
if (matrix.find_string())
std::cout << "find the string";
std::cout << "no this string";
system("pause");
return 0;
}