一、题目
二、题解
本题是单词搜索II的特殊情况,单词搜索II需要用到Trie树本题可以不使用Trie树但思想总体上相同,都是枚举所有可能的单词序列,看该序列是否是目标单词或者目标单词的前缀,如果是目标单词则之间返回,如果是前缀则继续dfs
const int N = 1e4 + 10;
class Solution {
public:
int son[N][128], cnt[N], idx, n, m; // son存储Trie树,cnt存储该位置结尾是否有单词,idx用于申请空间
vector<vector<char>> words; // 将字符矩阵参数全局
string path; // 记录dfs过程中的单词序列
bool check[10][10]; // dfs过程中用于标记已经选择的字符
bool dfs(int i, int j) {
path.push_back(words[i][j]);
check[i][j] = true;
if (search(path)) return true;
if (!prefix(path)) { // 剪枝
check[i][j] = false;
path.pop_back();
return false;
};
bool ans = false;
if (i - 1 >= 0 && !check[i - 1][j]) {
ans |= dfs(i - 1, j);
}
if (i + 1 < n && !check[i + 1][j]){
ans |= dfs(i + 1, j);
}
if (j - 1 >= 0 && !check[i][j - 1]) {
ans |= dfs(i, j - 1);
}
if (j + 1 < m && !check[i][j + 1]) {
ans |= dfs(i, j + 1);
}
check[i][j] = false;
path.pop_back();
return ans;
}
void insert(string path) {
int p = 0;
for (auto x : path) {
int childIndex = x - 'A';
if (!son[p][childIndex]) son[p][childIndex] = ++idx;
p = son[p][childIndex];
}
cnt[p]++;
}
bool search(string path) {
int p = 0;
for (auto x : path) {
int childIndex = x - 'A';
if (!son[p][childIndex]) return 0;
p = son[p][childIndex];
}
return cnt[p];
}
bool prefix(string path) {
int p = 0;
for (auto x : path) {
int childIndex = x - 'A';
if (!son[p][childIndex]) return 0;
p = son[p][childIndex];
}
return 1;
}
bool exist(vector<vector<char>>& board, string word) {
idx = 0;
memset(son, 0, sizeof(son));
memset(cnt, 0, sizeof(cnt));
insert(word);
words = board;
n = board.size(), m = board[0].size();
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (dfs(i, j))
return true;
return false;
}
};