class Solution {
public:
bool dfs(char* matrix, int row, int col, int rows, int cols, char* str, int len, vector<vector<bool> >& visit) {
if (str[len] == '\0') return true;
if (row < 0 || row >= rows || col < 0 || col >= cols) return false;
const int dx[4] = {-1,0,1,0};
const int dy[4] = {0,1,0,-1};
if (!visit[row][col] && matrix[row*cols+col] == str[len]) {
visit[row][col] = true;
for (int i = 0; i < 4; ++ i) {
if (dfs(matrix, row+dx[i], col+dy[i], rows, cols, str, len+1, visit)) return true;
}
visit[row][col] = false;
}
return false;
}
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if (matrix == NULL || rows == 0 || cols == 0 || str == NULL) return false;
vector<vector<bool> > visit(rows, vector<bool>(cols, false));
int len = 0;
for (int i = 0; i < rows; ++ i) {
for (int j = 0; j < cols; ++ j) {
if (dfs(matrix, i, j, rows, cols, str, len, visit)) return true;
}
}
return false;
}
};