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.
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; } }
相关文章推荐
- 212. Word Search II (DFS,trie)
- 212. Word Search II--python
- 212. Word Search II
- 212. Word Search II
- Leetcode 212. Word Search II
- LeetCode 212. Word Search II(单词搜索)
- Leetcode 212. Word Search II
- Hard-题目48:212. Word Search II
- 212. Word Search II(Trie)
- Leetcode 212. Word Search II
- 212. Word Search II
- 212. Word Search II[hard]
- [leetcode] 212. Word Search II 解题报告
- Leetcode 79. Word Search & 212. Word Search II
- 212. Word Search II 在二维字母表里找到给定word集合中的word子串
- Leetcode 212. Word Search II
- 212. Word Search II
- Leetcode 212. Word Search II
- 212. Word Search II
- LeetCode 212. Word Search II