304 North Cardinal St.
Dorchester Center, MA 02124

# Word Search II LeetCode Solution

## Problem – Word Search II

Given an `m x n` `board` of characters and a list of strings `words`, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Example 1:

``````Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]``````

Example 2:

``````Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []``````

Constraints:

• `m == board.length`
• `n == board[i].length`
• `1 <= m, n <= 12`
• `board[i][j]` is a lowercase English letter.
• `1 <= words.length <= 3 * 104`
• `1 <= words[i].length <= 10`
• `words[i]` consists of lowercase English letters.
• All the strings of `words` are unique.

### Word Search II LeetCode Solution in Java

``````public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
TrieNode root = buildTrie(words);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
dfs (board, i, j, root, res);
}
}
return res;
}

public void dfs(char[][] board, int i, int j, TrieNode p, List<String> res) {
char c = board[i][j];
if (c == '#' || p.next[c - 'a'] == null) return;
p = p.next[c - 'a'];
if (p.word != null) {   // found one
p.word = null;     // de-duplicate
}

board[i][j] = '#';
if (i > 0) dfs(board, i - 1, j ,p, res);
if (j > 0) dfs(board, i, j - 1, p, res);
if (i < board.length - 1) dfs(board, i + 1, j, p, res);
if (j < board.length - 1) dfs(board, i, j + 1, p, res);
board[i][j] = c;
}

public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String w : words) {
TrieNode p = root;
for (char c : w.toCharArray()) {
int i = c - 'a';
if (p.next[i] == null) p.next[i] = new TrieNode();
p = p.next[i];
}
p.word = w;
}
return root;
}

class TrieNode {
TrieNode[] next = new TrieNode;
String word;
}
``````

### Word Search II LeetCode Solution in Python

``````class TrieNode():
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.isWord = False

class Trie():
def __init__(self):
self.root = TrieNode()

def insert(self, word):
node = self.root
for w in word:
node = node.children[w]
node.isWord = True

def search(self, word):
node = self.root
for w in word:
node = node.children.get(w)
if not node:
return False
return node.isWord

class Solution(object):
def findWords(self, board, words):
res = []
trie = Trie()
node = trie.root
for w in words:
trie.insert(w)
for i in xrange(len(board)):
for j in xrange(len(board)):
self.dfs(board, node, i, j, "", res)
return res

def dfs(self, board, node, i, j, path, res):
if node.isWord:
res.append(path)
node.isWord = False
if i < 0 or i >= len(board) or j < 0 or j >= len(board):
return
tmp = board[i][j]
node = node.children.get(tmp)
if not node:
return
board[i][j] = "#"
self.dfs(board, node, i+1, j, path+tmp, res)
self.dfs(board, node, i-1, j, path+tmp, res)
self.dfs(board, node, i, j-1, path+tmp, res)
self.dfs(board, node, i, j+1, path+tmp, res)
board[i][j] = tmp
``````

### Word Search II LeetCode Solution in C++

``````class TrieNode{
public:
bool is_end;
vector<TrieNode*> children;
TrieNode(){
is_end=false;
children=vector<TrieNode*>(26, NULL);
}
};

class Trie{
public:
TrieNode* getRoot(){return root;}
Trie(vector<string>& words){
root=new TrieNode();
for(int i=0; i<words.size(); ++i)
}
void addWord(const string& word){
TrieNode* cur=root;
for(int i=0; i<word.size(); ++i){
int index=word[i]-'a';
if(cur->children[index]==NULL)
cur->children[index]=new TrieNode();
cur=cur->children[index];
}
cur->is_end=true;
}
private:
TrieNode* root;
};

class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Trie* trie = new Trie(words);
TrieNode* root=trie->getRoot();
set<string> result_set;
for(int x=0; x<board.size(); ++x)
for(int y=0; y<board.size(); ++y)
findWords(board, x, y, root, "", result_set);

vector<string> result;
for(auto it:result_set)    result.push_back(it);
return result;
}
private:
void findWords(vector<vector<char>>& board, int x, int y, TrieNode* root, string word, set<string>& result){
if(x<0||x>=board.size()||y<0||y>=board.size() || board[x][y]==' ') return;

if(root->children[board[x][y]-'a'] != NULL){
word=word+board[x][y];
root=root->children[board[x][y]-'a'];
if(root->is_end) result.insert(word);
char c=board[x][y];
board[x][y]=' ';
findWords(board, x+1, y, root, word, result);
findWords(board, x-1, y, root, word, result);
findWords(board, x, y+1, root, word, result);
findWords(board, x, y-1, root, word, result);
board[x][y]=c;
}
}
};
``````
##### Word Search II LeetCode Solution Review:

In our experience, we suggest you solve this Word Search II LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Word Search II LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Word Search II LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions