暴力回溯
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix string字符串
* @param rows int整型
* @param cols int整型
* @param str string字符串
* @return bool布尔型
*/
bool _backtrack(const std::string& matrix, std::vector<bool>& is_visited, int rows, int cols,
int i, int j, const std::string& str, int idx)
{
if(idx == str.length())
{
return true;
}
if(i < 0 || i >= rows || j < 0 || j >= cols || is_visited[cols * i + j] || matrix[cols * i + j] != str[idx])
{
return false;
}
is_visited[cols * i + j] = true;
bool r = _backtrack(matrix, is_visited, rows, cols, i + 1, j, str, idx + 1)
|| _backtrack(matrix, is_visited, rows, cols, i - 1, j, str, idx + 1)
|| _backtrack(matrix, is_visited, rows, cols, i, j + 1, str, idx + 1)
|| _backtrack(matrix, is_visited, rows, cols, i, j - 1, str, idx + 1);
is_visited[cols * i + j] = false;
return r;
}
bool hasPath(string matrix, int rows, int cols, string str)
{
std::vector<bool> is_visited(rows * cols, false);
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < cols; ++j)
{
if(_backtrack(matrix, is_visited, rows, cols, i, j, str, 0))
{
return true;
}
}
}
return false;
}
};
京公网安备 11010502036488号