// test20.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<cstring>
#include<string.h>
#include<deque>
#include <forward_list>
using namespace std;
class Solution {
public:
char* flag;
bool hasPath(char* matrix, int rows, int cols, char* str)
{
flag = str;
if (matrix == NULL || str == NULL) return false;
char* current = matrix;
char* tempStr= matrix;
bool result = false;
while (tempStr <matrix +rows*cols)
{
/* cout << "*current:" << *current << " ";
cout << "*str:" << *str << endl;*/
if (*tempStr == *str)
{
visisted.clear();//不要忘了清楚visisted!!!!!!!!!!!!!!(问题1)
setVisisted(rows, cols);
char* current = tempStr;
cout << "*current:" << *current << " ";
cout << "*str:" << *str << endl;
result = getPath(matrix,rows,cols, str, current);
cout << endl << endl;;
}
if (result == true) break;
++tempStr;
}
return result;
}
bool getPath(char* matrix, int rows, int cols, char* str, char* current)
{
if (*str == '\0')return true;//注意:此句话放在不同的位置得出的结论是不同的,不能放在下面的位置!!!!!!!!!!!!!(问题3)
if (current < matrix || current >= matrix + rows*cols) return false;
if(visisted[current - matrix]==true)return false;
// visisted[current - matrix] = true;//当该数符合要求才设置为true!!!!!!!!!!!!!!设置在此处是错误的!!!!!!!!!!(问题2)
//if (*str == '\0')return true;//注意,!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
cout << "*str:" << *str << " ";
cout << "*current:" << *current << endl;
cout << "str的下标:" << str - flag<<" " ;
cout << "current的下标:" << current - matrix << endl;
if (*str != *current) return false;
//if (*str == *current)//两者相等
visisted[current - matrix] = true;//当该数符合要求才设置为true!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return getPath(matrix, rows, cols, str + 1, current - 1) ||
getPath(matrix, rows, cols, str + 1, current + 1) ||
getPath(matrix, rows, cols, str + 1, current - cols) ||
getPath(matrix, rows, cols, str + 1, current + cols);
}
vector<bool> visisted;//访问标志数组,如果已经被访问,则设置为true,以后不可被访问
void setVisisted(int rows,int cols)
{
int i = 0;
while (i<rows*cols)
{
visisted.push_back(false);
++i;
}
}
};
int main()
{
Solution so;
//cout << 1 / 10 << endl;
//char* matrix = "abcesfcsadee";
//char* matrix = "ABCEHJIGSFCSLOPQADEEMNOEADIDEJFMVCEIFGGS";
//char* str = "SLHECCEIDEJFGGFIE";
char* matrix = "AAAAAAAAAAAA";
char* str = "AAAAAAAAAAAA";
char* str1 = "bcced";
char* str2 = "abcb";
char* str3 = "abc";
int rows = 3;
int cols = 4;
//cout<<"bcced匹配结果是:"<<so.hasPath(matrix, rows, cols, str1)<<endl;
//cout << "abcb匹配结果是:" << so.hasPath(matrix, rows, cols, str2) << endl;
//cout << "abc匹配结果是:" << so.hasPath(matrix, rows, cols, str3) << endl;
cout << "SLHECCEIDEJFGGFIE匹配结果是:" << so.hasPath(matrix, 3, 4, str) << endl;
return 0;
}