目录
牛客_NC242 单词搜索(dfs)
解析代码
简单dfs深搜应用题,dfs深搜学习博客:
Offer必备算法31_DFS回溯剪枝_九道力扣题详解(由易到难)_力扣dfs经典题-CSDN博客
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param board string字符串vector
* @param word string字符串
* @return bool布尔型
*/
int dx[4] = { 0, 0, -1, 1 };
int dy[4] = { 1, -1, 0, 0 };
bool vis[101][101];
int m = 0, n = 0;
bool exist(vector<string>& board, string word) {
m = board.size(), n = board[0].size();
if (word.size() > m * n)
return false;;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (board[i][j] == word[0])
{
if (dfs(board, i, j, 0, word) == true) // 从0开始写成从1开始的版本,然后几个用例没过
return true;
}
}
}
return false;
}
bool dfs(vector<string>& board, int sr, int sc, int pos, string& word)
{
if (pos == word.size() - 1)
return true;
vis[sr][sc] = true;
for (int i = 0; i < 4; ++i)
{
int x = sr + dx[i], y = sc + dy[i];
if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && word[pos + 1] == board[x][y]) // pos少+1了
{
// if(pos == word.size())
// return true;
// return dfs(board, x, y, pos + 1, word);
// 这两行写成上一行了
if(dfs(board, x, y, pos + 1, word))
return true;
}
}
vis[sr][sc] = false; // 恢复现场!!!!!!!!!!!这行没写
return false;
}
};