题目:
Given a set of words (without duplicates), find all word squares you can build from them.
A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
For example, the word sequence ["ball","area","lead","lady"]
forms a word square because each word reads the same both horizontally and vertically.
b a l l a r e a l e a d l a d y
Note:
- There are at least 1 and at most 1000 words.
- All words will have the exact same length.
- Word length is at least 1 and at most 5.
- Each word contains only lowercase English alphabet
a-z
.
Example 1:
Input: ["area","lead","wall","lady","ball"] Output: [ [ "wall", "area", "lead", "lady" ], [ "ball", "area", "lead", "lady" ] ] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
Example 2:
Input: ["abat","baba","atan","atal"] Output: [ [ "baba", "abat", "baba", "atan" ], [ "baba", "abat", "baba", "atal" ] ] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matt
思路:
还是那句老话:对于需要求出所有可行解的问题来讲,BackTracking都是不二选择(至少从我目前遇到的Leetcode题目来讲都是如此)。对于本题而言,我们同样可以采用BackTracking,逐个试着加每个word,一旦发现solution的size已经和word的length一样了,并且还没有违反Word Square的规则,那么该solution就是一个可行解,把它加入解集就可以了。当采用深度优先搜索(dfs)获得所有可行的solution之后,返回即可。
当然作为难度为hard的Leetcode题目而言,不可能这么简单的让你通过测试。由于涉及大量的搜索words中的单词,以及判断某个单词加入之后是否仍然符合word square的规则,所以采用暴力搜索肯定会超时。幸亏我们在前面的题目中多次采用过Trie这种数据结构,来加速对包含通配符在内的单词的搜索,这里刚好就派上用场了!怎么做呢?1)把words里面的所有单词加入Trie中,建立一个字典树。2)采用BackTracking的策略来求得符合条件的所有解(这个过程里面还有一些技巧,请看下面代码片段的注释)。
代码:
class TrieNode
{
public:
bool isComplete;
TrieNode* ch[26];
TrieNode() {
isComplete = false;
for(int i = 0; i < 26; ++i) {
ch[i] = NULL;
}
}
};
class Trie
{
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* p = root;
for(auto c : word) {
if(p->ch[c - 'a'] == NULL)
p->ch[c - 'a'] = new TrieNode();
p = p->ch[c - 'a'];
}
p->isComplete = true;
}
void search(TrieNode* p, string& word, int startIndex, string line, vector<string> &ret) {
if(p == NULL)
return;
if(startIndex == word.length()) {
if(p->isComplete) {
ret.push_back(line);
}
return;
}
char c = word[startIndex];
if(c != '.') {
search(p->ch[c-'a'], word, startIndex + 1, line + c, ret);
}
else {
for(int i = 0; i < 26; ++i) {
if(p->ch[i] != NULL) {
char temp_c = 'a' + i;
search(p->ch[i], word, startIndex + 1, line + temp_c, ret);
}
}
}
}
TrieNode* getRoot() {
return root;
}
private:
TrieNode* root;
};
class Solution {
public:
vector<vector<string>> wordSquares(vector<string>& words) {
vector<vector<string>> ret;
if(words.size() == 0 || words[0].length() == 0) {
return ret;
}
int word_length = words[0].length();
Trie trie; // build the Trie
for(int i = 0; i < words.size(); ++i) {
trie.insert(words[i]);
}
vector<string> solution;
for(int i = 0; i < words.size(); ++i) { // try to put word[i] to the solution
solution.push_back(words[i]);
dfs(trie, word_length, ret, solution);
solution.pop_back(); // backtracking
}
return ret;
}
private:
void dfs(Trie& trie, int word_length, vector<vector<string>> &ret, vector<string> &solution) {
if(solution.size() == word_length) {
ret.push_back(solution);
return;
}
int size = solution.size();
string word; // Find how the word should be. '.' means any letter can be here
for(int i = 0; i < word_length; ++i) {
if(i < size) {
word += solution[i][size];
}
else {
word += '.';
}
}
vector<string> candidates; // Collect the possible words that fullfill the structure of word
trie.search(trie.getRoot(), word, 0, "", candidates);
for(int i = 0; i < candidates.size(); ++i) { // Backtracking to find all the possible solutions
solution.push_back(candidates[i]);
dfs(trie, word_length, ret, solution);
solution.pop_back();
}
}
};