https://leetcode.com/problems/word-search-ii/
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example,
Given words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"].
首先是我最擅长的递归(DFS):
class Solution {
public:
/************************************************************************/
/*在一个二维字符矩阵里面找到相邻元素能够拼接成word*/
/************************************************************************/
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string>res;
unordered_set<string>cache;
for (auto x:words)
{
if (cache.find(x) == cache.end())
{
cache.insert(x);
if (findAWord(board, x))
res.push_back(x);
}
}
return res;
}
bool findAWord(const vector<vector<char>>& board, string s)
{
//考虑每个s[i]可能在多个位置上出现
//用递归
int n = board.size();
int m = board[0].size();
vector<vector<bool>>used(n, vector<bool>(m, false));
for (int i=0;i<n;++i)
{
for (int j=0;j<m;++j)
{
if (board[i][j] == s[0])
{
used[i][j] = true;
if (__findAWords(board, used,i,j, s.substr(1)))return true;
used[i][j] = false;
}
}
}
return false;
}
bool __findAWords(const vector<vector<char>>& board, vector<vector<bool>>&used, int x, int y, string s)
{
if (s.size() == 0)return true;
//上下左右四个方向的检测
if (x > 0)//shang
{
if (used[x - 1][y] == false && board[x - 1][y] == s[0])
{
used[x - 1][y] = true;
if (__findAWords(board, used, x-1, y, s.substr(1)))return true;
used[x - 1][y] = false;
}
}
if (x < board.size()-1)//下
{
if (used[x + 1][y] == false && board[x + 1][y] == s[0])
{
used[x + 1][y] = true;
if (__findAWords(board, used, x + 1, y, s.substr(1)))return true;
used[x + 1][y] = false;
}
}
if (y > 0)//左
{
if (used[x][y-1] == false && board[x][y-1] == s[0])
{
used[x][y-1] = true;
if (__findAWords(board, used, x, y-1, s.substr(1)))return true;
used[x][y-1] = false;
}
}
if (y < board[0].size()-1)//右
{
if (used[x][y+1] == false && board[x][y+1] == s[0])
{
used[x][y+1] = true;
if (__findAWords(board, used, x, y+1, s.substr(1)))return true;
used[x][y+1] = false;
}
}
return false;
}
};
有三个函数组成
第一个遍历words所有的word,对每一个word进行查找
第二个,查找函数,传递used数组,标记board的使用
第三个,递归函数, 截止条件,上下左右的查找
幸运的是:这种做法能够把word search I里面的AC
遗憾的是:Time Limit Exceeded
此版本的改进版:
public boolean exist(char[][] board, String word) {
char[] w = word.toCharArray();
for (int y=0; y<board.length; y++) {
for (int x=0; x<board[y].length; x++) {
if (exist(board, y, x, w, 0)) return true;
}
}
return false;
}
private boolean exist(char[][] board, int y, int x, char[] word, int i) {
if (i == word.length) return true;
if (y<0 || x<0 || y == board.length || x == board[y].length) return false;
if (board[y][x] != word[i]) return false;
board[y][x] ^= 256;
boolean exist = exist(board, y, x+1, word, i+1)
|| exist(board, y, x-1, word, i+1)
|| exist(board, y+1, x, word, i+1)
|| exist(board, y-1, x, word, i+1);
board[y][x] ^= 256;
return exist;
}
改进的地方在于:
1. 使用mask代替了used标记数组,巧妙
2. 递归开始的和截止地方有些差异,这种改进更清晰,明显缩短代码量
解决word search II
使用tries字典树对words进行预处理,然后dfs
struct TrieNode
{
//只有小写字母
TrieNode* next[26];
string nodecontent;
TrieNode()
{
<span style="white-space:pre"> </span>for(int i=0;i<26;i++)next[i]=nullptr; //初始全部为NULL
nodecontent = string(""); //赋值空
}
};
//有很多string 构造成的root node
TrieNode* getTrieroot(const vector<string>&vs)
{
TrieNode* root=new TrieNode();
for (string x:vs) //注意此处的技巧,遍历所有的string
{
TrieNode* p = root;
for (char c:x)
{
int i = c - 'a'; //所有char都是小写字母
if (p->next[i]==NULL) //在字典树中,每个节点可能有26个可能,只适合此题的情况
{
p->next[i] = new TrieNode();
}
p = p->next[i]; //对一个string全部遍历完
}
p->nodecontent = x; //最后的node存储这个string
}
return root;
}
class Solution
{
public:
/************************************************************************/
/*在一个二维字符矩阵里面找到相邻元素能够拼接成word*/
//使用 tries字典树和dfs
/************************************************************************/
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string>res;
TrieNode* root = getTrieroot(words); //转为字典树
for (int i=0;i<board.size();++i)
{
for (int j=0;j<board[0].size();++j)
{
findWordsDFS(board, i, j, root, res); //对每一个位置,DFS
}
}
return res;
}
void findWordsDFS(vector<vector<char>>& board, int i, int j, TrieNode* root, vector<string>&res)
{
char c = board[i][j];
if (c == '#' || root->next[c - 'a'] == NULL)return; //赋值为'#'表示当前节点已经访问过了了
root = root->next[c - 'a']; //当前节点不存储,指向下一个节点
if (root->nodecontent.size()!=0)
{
res.push_back(root->nodecontent);
root->nodecontent.clear(); //去重,既然这个string已经找到了,那就在字典树里面删除它,防止board其它路劲也可以找到这个string
}
board[i][j] = '#';//当前这个位置已经访问了
if (j > 0)findWordsDFS(board, i, j - 1, root, res);
if (i > 0)findWordsDFS(board, i - 1, j, root, res);
if (j < board[0].size() - 1)findWordsDFS(board, i, j + 1, root, res);
if (i < board.size() - 1)findWordsDFS(board, i + 1, j, root, res);
board[i][j] = c;
}
private:
};
巧妙地利用了字典树,遍历二维board里面的每个点的时候,对所有的需要匹配的word信息进行了关联,而不用想当个word那种一个个单次匹配。