给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例 1:
输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
输出:["eat","oath"]
示例 2:
输入:board = [["a","b"],["c","d"]], words = ["abcb"]
输出:[]
提示:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] 是一个小写英文字母
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] 由小写英文字母组成
words 中的所有字符串互不相同
题解
Trie+暴力搜索
class Solution {
public:
static const int N = 3e4 + 10;
int trie[N][26],cnt[N],idx;
void insertstring &t){
int p = 0;
forauto &c : t){
int u = c - 'a';
iftrie[p][u] == 0)trie[p][u] = ++idx;
p = trie[p][u];
ifcnt[p] != 1)cnt[p] = -1;
}
cnt[p] = 1;
}
vector<string>res;
string t = "";
int n,m;
int vis[12][12],dx[4] = {
0,1,0,-1},dy[4] = {
-1,0,1,0};
int flag[N] = {
0};
set<string>ss;
void dfsint x,int y,vector<vector<char>>& board,int p){
ifcnt[p] == 1){
ifflag[p] == 0)res.push_backt),flag[p] = 1;
}else ifcnt[p] == 0){
return;
}
ifx < 0 || x >= n || y < 0 || y >= m)return;
ifvis[x][y])return;
vis[x][y] = true;
t.append1,board[x][y]);
forint k = 0;k < 4;k ++){
int a = x + dx[k],b = y + dy[k];
iftrie[p][board[x][y] - 'a'] != 0)
dfsa,b,board,trie[p][board[x][y] - 'a']);
}
t.eraset.size) - 1,1);
vis[x][y] = false;
}
vector<string> findWordsvector<vector<char>>& board, vector<string>& words) {
forauto &word : words)insertword);
cnt[0] = -1;
n = board.size),m = board[0].size);
forint i = 0;i < n;i ++){
forint j = 0;j < m;j ++){
dfsi,j,board,0);
}
}
return res;
}
};