//请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
//路径可以从矩阵中任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条
//路径经过了矩阵的某一格,那么该路径不能再次进入该格子。
#include "iostream"
#include "vector"
using namespace std;
//回溯法
void construct_candidates(vector<pair<int, int> >& c, pair<int, int>& current,
char next, char** mat, vector<vector<bool> >& accessible)
{
int rows = accessible.size();
int cols = accessible[0].size();
int x = current.first;
int y = current.second;
if (x-1 >= 0 && mat[x-1][y] == next && accessible[x-1][y]) c.push_back(make_pair(x - 1, y));
if (y - 1 >= 0 && mat[x][y - 1] == next && accessible[x][y - 1]) c.push_back(make_pair(x, y - 1));
if (x + 1 < rows && mat[x + 1][y] == next && accessible[x + 1][y]) c.push_back(make_pair(x + 1, y));
if (y + 1 < cols && mat[x][y + 1] == next && accessible[x][y + 1]) c.push_back(make_pair(x, y + 1));
}
void backTracking(vector<pair<int, int> >& path, vector<vector<bool> >& accessible,
char** mat, char* str, bool* found)
{
if (path.size() == strlen(str))
*found = true;
else
{
vector<pair<int, int> >c;
construct_candidates(c, path.back(), str[path.size()], mat, accessible);
for (size_t i = 0; i < c.size(); ++i)
{
int nx = c[i].first;
int ny = c[i].second;
path.push_back(c[i]);
accessible[nx][ny] = false;
backTracking(path, accessible, mat, str, found);
if (*found)
break;
path.pop_back();
accessible[nx][ny] = true;
}
}
}
bool hasPath(char** mat, int rows, int cols, char* str)
{
if (mat == NULL || str == NULL || rows <= 0 || cols <= 0)
return false;
vector<pair<int, int> > path;
vector<vector<bool> >accessible(rows, vector<bool>(cols, true));
bool found = false;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (mat[i][j] == str[0])
{
path.push_back(make_pair(i, j));
backTracking(path, accessible, mat, str, &found);
}
if (found)
return found;
}
}
return found;
}
void test()
{
char *mat[] = { "abce", "sfcs", "adee" };
char str[] = "bcced";
cout << boolalpha << hasPath(mat, 3, 4, str) << endl;
}
int main()
{
test();
return 0;
}