您的位置:首页 > 其它

212. Word Search II

2017-03-04 19:32 351 查看
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”].

Note:

You may assume that all inputs are consist of lowercase letters a-z.

public class Solution {
class TrieNode {
TrieNode[] next = new TrieNode[26];
String word;
}
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList<String>();
TrieNode root = buildTrie(words);
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
dfs(board, i, j, root, result);
}
}
return result;
}
public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (int i = 0; i < words.length; i++) {
String word = words[i];
TrieNode pnode = root;
for (char c : word.toCharArray()) {
if(pnode.next[c-'a'] == null) pnode.next[c-'a'] = new TrieNode();
pnode = pnode.next[c-'a'];
}
pnode.word = word;
}
return root;
}
public void dfs(char[][] board, int i, int j, TrieNode root, List<String> res) {
char c = board[i][j];
if(c == '#' || root.next[c-'a'] == null) return;
root = root.next[c-'a'];
if(root.word != null) {
res.add(root.word);
root.word = null;
}
board[i][j] = '#';
if(i > 0) dfs(board, i-1, j, root, res);
if(j > 0) dfs(board, i, j-1, root, res);
if(i < board.length-1) dfs(board, i+1, j, root, res);
if(j < board[0].length-1) dfs(board, i, j+1, root, res);
board[i][j] = c;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: