字符矩阵中找字符串路径

#include<iostream>
#include<string>
#include<vector>
using namespace std;
class solution{
public:
vector<int>::iterator iter;
bool hascore(const char* Matrix, char* str, const int cols, const int rows, int row, int col, int& pathlength, bool* visited)//
{
if ((str[pathlength]) == '\0')//终止情况
return true;
bool haspath = false;
if (row>=0&&col>=0&&Matrix[row*cols + col] == str[pathlength] && !visited[row*cols + col])//推理演进
{
path.push_back(row);
path.push_back(col);
pathlength++;
visited[row*cols + col]=1;
haspath = (hascore(Matrix, str, cols, rows, row, col - 1, pathlength, visited) //四次递归调用
|| hascore(Matrix, str, cols, rows, row - 1, col, pathlength, visited) 
|| hascore(Matrix, str, cols, rows, row, col + 1, pathlength, visited)
|| hascore(Matrix, str, cols, rows, row + 1, col, pathlength, visited));
if (!haspath)
{
pathlength--;
visited[row*cols + col]=0;
return false;
path.clear();
}
}
return haspath;
}
bool haspath(const char* Matrix,char* str,int& cols,int& rows)
{
if (Matrix == nullptr || str == nullptr || cols < 1 || rows < 1)
return false;
bool* visited = new bool[cols*rows];
memset(visited, 0, cols*rows);
int pathlength = 0;
bool re=false;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
re=hascore(Matrix, str,cols,rows, i, j ,pathlength,visited);
if (re)
return true;
}
}
return re;
}
bool test(const char* Maxtrix, int rows, int cols,  char* str)
{
if (haspath(Maxtrix, str, cols, rows))
{
cout <<"result:"<<' '<<"passed" << endl;
cout << "path:"<<endl;
for (iter = path.begin(); iter != path.end(); iter++)
{
cout << *iter;
cout << *(++iter);
if (iter != path.end()-1)
cout << "->";
}
cout << endl;
}
else
return false;
}
private:
vector<int> path;
};
int main()
{
solution s;
char* Matrix = "ABTGCFCSJDEH";
char* str = "ABTC";
cout << "Matrix:" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
cout << Matrix[i * 4 + j]<<' ';
}
cout << endl;
}
cout << "pathstring:" << endl;
for (int i = 0; i < 4; i++)
{
cout << str[i] << ' ';
}
cout << endl;
bool re=s.test(Matrix, 3, 4,str);
if (!re)
cout << "result: "<<"denyed"<<endl;
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值