#include <vector>
#include <iostream>
using namespace std;
class solution
{
public:
bool has_path(vector<char> matrix, int rows, int cols, const char* str)
{
if (!matrix.size() || rows < 1 || cols < 1 || !str)
return false;
vector<bool> visited(matrix.size(), false);
int path_len = 0;
for (int row = 0; row < rows; ++row)
{
for (int col = 0; col < cols; ++col)
{
if (find_path(matrix, visited, path_len, rows, cols, row, col, str))
{
return true;
}
}
}
return false;
}
bool find_path(vector<char> matrix, vector<bool> visited, int& path_len,
int rows, int cols, int row, int col, const char* str)
{
if (str[path_len] == '\0')
return true;
bool find_the_path = false;
if (row >= 0 && row < rows &&col >= 0 && col < cols &&
str[path_len] == matrix[row*cols + col] && !visited[row*cols + col])
{
++path_len;
visited[row*cols + col] = true;
find_the_path = find_path(matrix, visited, path_len, rows, cols, row, col + 1, str)
|| find_path(matrix, visited, path_len, rows, cols, row, col - 1, str)
|| find_path(matrix, visited, path_len, rows, cols, row + 1, col, str)
|| find_path(matrix, visited, path_len, rows, cols, row - 1, col, str);
if (!find_the_path)
{
--path_len;
visited[row*cols + col] = false;
}
}
return find_the_path;
}
};
int main()
{
vector<char> matrix = { 'a','b','t','g','c','f','c','s','j','d','e','h' };
int rows = 3, cols = 4;
char str1[] = "bfce";
char str2[] = "bfcsh";
char str3[] = "abtcedjcf";
char str4[] = "afch";
solution a;
bool b1 = a.has_path(matrix, rows, cols, str1);
bool b2 = a.has_path(matrix, rows, cols, str2);
bool b3 = a.has_path(matrix, rows, cols, str3);
bool b4 = a.has_path(matrix, rows, cols, str4);
cout << boolalpha << b1 << " " << b2 << " " << b3 << " " << b4 << endl;
system("pause");
}