题目:给定一个字符矩阵和一个字符串,判断该字符串是否出现在矩阵中,路径可以从矩阵中的任意一格开始,每一步只能向左、向右、向上、向下移动。例如,在3*4的矩阵abce,sfcs,adee中含有字符串bcced路径,但是不含有字符串adcb路径。
解析:这是一道经典的回溯题,(1)从矩阵中的每个字符开始和字符串比较,如果矩阵中的字符和字符串中的字符相等,则在矩阵中向左、向右、向上、向下移动,直到不等为止。
bool helper(char *matrix, int rows, int cols, char *str,int row, int col, int len, vector<bool> &visited)
{
if (str[len] == '\0')
return true;
bool flag = false;
if (row < rows && row >= 0
&& col < cols && col >= 0
&&str[len] == matrix[row *cols + col]
&& !visited[row*cols + col])
{
visited[row*cols + col] = true;
flag = helper(matrix, rows, cols, str, row + 1, col, len + 1, visited)
|| helper(matrix, rows, cols, str, row - 1, col, len + 1, visited)
|| helper(matrix, rows, cols, str, row, col + 1, len + 1, visited)
|| helper(matrix, rows, cols, str, row, col - 1, len + 1, visited);
if (!flag)
{
visited[row*cols + col] = false;
len--;
}
}
return flag;
}
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if (matrix == NULL || rows <= 0 || cols <= 0 || str == NULL)
return false;
vector<bool> flag(rows*cols);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
if (helper(matrix, rows, cols, str, row, col, 0, flag))
{
return true;
}
}
}
return false;
}