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.
Note:
All inputs are consist of lowercase letters a-z.
The values of words are distinct.
Constraints
Approach
Links
GeeksforGeeks
ProgramCreek
YouTube
Examples
Solutions
/**
* Time complexity :
* Space complexity :
*/
class Solution {
class TrieNode {
TrieNode[] children = new TrieNode[26];
String word = null;
}
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList();
if(board == null || board.length == 0) {
return result;
}
TrieNode trieNode = buildTrie(words);
int row = board.length,
col = board[0].length;
for(int r = 0; r < row; r++) {
for(int c = 0; c < col; c++) {
dfs(board, r, c, trieNode, result);
}
}
return result;
}
private void dfs(char[][] board,
int r,
int c,
TrieNode trieNode,
List<String> result
) {
int row = board.length,
col = board[0].length;
if(r < 0 || r >= row || c < 0 || c >= col) return;
if(board[r][c] == '#' ||
trieNode.children[board[r][c]-'a'] == null) return;
char ch = board[r][c];
trieNode = trieNode.children[board[r][c]-'a'];
if(trieNode.word != null) {
result.add(trieNode.word);
trieNode.word = null;
}
board[r][c] = '#';
dfs(board, r+1, c, trieNode, result);
dfs(board, r-1, c, trieNode, result);
dfs(board, r, c+1, trieNode, result);
dfs(board, r, c-1, trieNode, result);
board[r][c] = ch;
}
private TrieNode buildTrie(String[] words) {
TrieNode trieNode = new TrieNode();
for(String word: words) {
TrieNode currNode = trieNode;
for(char ch: word.toCharArray()) {
if(currNode.children[ch-'a'] == null) {
currNode.children[ch-'a'] = new TrieNode();
}
currNode = currNode.children[ch-'a'];
}
currNode.word = word;
}
return trieNode;
}
}