79. 单词搜索
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
输出:true
示例 2:
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “SEE”
输出:true
示例 3:
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCB”
输出:false
在dfs中先枚举单词的起点,之后依次枚举单词的每个字母,枚举到该字母的时候将已经使用过的字母替换成另一个字母,避免重复枚举。
class Solution {
public:
vector<vector<char>> g;
int n,m;
bool exist(vector<vector<char>>& board, string word) {
g=board;
n=board.size(),m=board[0].size();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(dfs(word,0,i,j)) return true;
}
}
return false;
}
bool dfs(string word,int u,int x,int y)
{
if(g[x][y]!=word[u]) return false;
if(u==word.size()-1) return true;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
char t=g[x][y];
g[x][y]='*';
for(int i=0;i<4;i++)
{
int a=x+dx[i],b=y+dy[i];
if(a>=0 && a<n && b>=0 && b<m )
{
if(dfs(word,u+1,a,b)) return true;
}
}
g[x][y]=t;
return false;
}
};
212 单词搜索 II
给定一个 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”]
输出:[]
题解:
暴力枚举每个单词,首先枚举每个单词的起始位置,然后向四个方向扩展,但是这样搜索会超时,需要使用字典树优化主要是对搜索路径剪枝,如果发现当前点在字典树路径中存在,那么继续搜索。
本题目主要是在DFS的基础上增加了字典树这一数据结构。需要手动写字典树,字典树最主要的操作是插入操作。除此之外需要使用一个id来记录在遍历过程中经过的单词。
class Solution {
public:
struct Node
{
int id;
Node* son[26];
Node()
{
id=-1;
for(int i=0;i<26;i++)
{
son[i]=0;
}
}
};
Node *root;
void insert(string word,int id)
{
Node* p =root;
for(auto c:word)
{
int u=c-'a';
if(!p->son[u]) p->son[u]=new Node();
p=p->son[u];
}
p->id=id;
}
vector<vector<char>> g;
set<int> ids;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
g=board;
root=new Node();
for(int i=0;i<words.size();i++) insert(words[i],i);
for(int i=0;i<g.size();i++)
{
for(int j=0;j<g[0].size();j++)
{
int u=g[i][j]-'a';
if(root->son[u])//如果该节点存在则遍历
{
dfs(i,j,root->son[u]);
}
}
}
vector<string> res;
for(auto id:ids) res.push_back(words[id]);
return res;
}
void dfs(int x,int y,Node* p)
{
if(p->id!=-1) ids.insert(p->id);//如果该节点是一个完整的单词,加入到该结果集合中。
char t = g[x][y];
g[x][y]='.';
for(int i=0;i<4;i++)
{
int a=x+dx[i],b=y+dy[i];
if(a>=0 &&a<g.size() && b>=0 &&b<g[0].size() && g[a][b]!='.')
{
int u=g[a][b]-'a';
if(p->son[u]) dfs(a,b,p->son[u]);
}
}
g[x][y]=t;
}
};