用Trie树方式实现
#define cti(x) (x-'a')
#define itc(x) (x+'a')
const int maxn = 70005;
const int sigma_size = 26;
class Solution {
public:
int ch[maxn][sigma_size], val[maxn] = {}, sz = 0;
void _insert(string word) {
int o = 0;
for (int i = 0; i < word.size(); ++i) {
if (!ch[o][cti(word[i])])
memset(ch[sz], 0, sizeof(ch[sz])), val[sz] = 0, ch[o][cti(word[i])] = sz++;
o = ch[o][cti(word[i])];
}
val[o] = 1;
}
vector<string> ans;
set<string> A;
vector<vector<bool>> vis;
string tmp;
int n, m, dx[4] = { -1,1,0,0 }, dy[4] = { 0,0,1,-1 };
bool _place(int i, int j) { return i >= 0 && i < n &&j >= 0 && j < m; }
bool dfs(vector<vector<char>>& board, int o, int row, int col) {
if (val[o] == 1) {
if (!A.count(tmp)) A.insert(tmp), ans.push_back(tmp);
}
for (int k = 0; k < 4; ++k) {
int i = row + dx[k], j = col + dy[k];
if (_place(i, j) && !vis[i][j] && ch[o][cti(board[i][j])]) {
vis[i][j] = 1;
tmp.push_back(board[i][j]);
dfs(board, ch[o][cti(board[i][j])], i, j);
tmp.pop_back();
vis[i][j] = 0;
}
}
return false;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
sz = 1, memset(ch[0], 0, sizeof(ch[0]));
for (auto& x : words)
_insert(x);
n = board.size(), m = n == 0 ? 0 : board[0].size();
vis.assign(n, vector<bool>(m, false));
for (int i = 0; i<n; ++i) {
for (int j = 0; j<m; ++j)
if (ch[0][cti(board[i][j])]) {
vis[i][j] = 1;
tmp.push_back(board[i][j]);
dfs(board, ch[0][cti(board[i][j])], i, j);
tmp.pop_back();
vis[i][j] = 0;
}
}
return ans;
}
};
暴力实现,勉强过
class Solution {
public:
vector<vector<bool>> vis;
int n, m, dx[4] = { -1,1,0,0 }, dy[4] = { 0,0,1,-1 };
bool _place(int i, int j) { return i >= 0 && i < n &&j >= 0 && j < m; }
bool dfs(vector<vector<char>>& board, string &word, int index, int row, int col) {
if (index == word.size()) return true;
for (int k = 0; k < 4; ++k) {
int i = row + dx[k], j = col + dy[k];
if (_place(i, j) && !vis[i][j] && board[i][j] == word[index]) {
vis[i][j] = 1;
if (dfs(board, word, index + 1, i, j)) return true;
vis[i][j] = 0;
}
}
return false;
}
bool exist(vector<vector<char>>& board, string word) {
n = board.size(), m = n == 0 ? 0 : board[0].size();
vis.assign(n, vector<bool>(m, false));
for (int i = 0; i<n; ++i)
for (int j = 0; j<m; ++j)
if (board[i][j] == word[0]) {
vis[i][j] = 1;
if (dfs(board, word, 1, i, j)) return true;
vis[i][j] = 0;
}
return false;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> ans;
sort(words.begin(), words.end());
string pre = "";
for (auto& x : words) {
if (x != pre && exist(board, x)) ans.push_back(x);
pre = x;
}
return ans;
}
};