Word Search II
Posted flagyuri
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Word Search II相关的知识,希望对你有一定的参考价值。
Given a matrix of lower alphabets and a dictionary. Find all words in the dictionary that can be found in the matrix. A word can start from any position in the matrix and go left/right/up/down to the adjacent position. One character only be used once in one word. No same word in dictionary
Example
Example 1:
Input:["doaf","agai","dcan"],["dog","dad","dgdg","can","again"]
Output:["again","can","dad","dog"]
Explanation:
d o a f
a g a i
d c a n
search in Matrix,so return ["again","can","dad","dog"].
Example 2:
Input:["a"],["b"]
Output:[]
Explanation:
a
search in Matrix,return [].
Challenge
Using trie to implement your algorithm.
使用了 Trie 的版本
考点:
- 字典树
- dfs
- tip:Tire树,一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。
题解:
- 首先建立字典树,字典树从root开始,每个节点利用hashmap动态开点,利用字母的公共前缀建树。
- 遍历字母矩阵,将字母矩阵的每个字母,从root开始dfs搜索,搜索到底部时,将字符串存入答案返回即可。
class TrieNode { //定义字典树的节点 String word; HashMap<Character, TrieNode> children; //使用HashMap动态开节点 public TrieNode() { word = null; children = new HashMap<Character, TrieNode>(); } }; class TrieTree{ TrieNode root; public TrieTree(TrieNode TrieNode) { root = TrieNode; } public void insert(String word) { //字典树插入单词 TrieNode node = root; for (int i = 0; i < word.length(); i++) { if (!node.children.containsKey(word.charAt(i))) { node.children.put(word.charAt(i), new TrieNode()); } node = node.children.get(word.charAt(i)); } node.word = word; } }; public class Solution { /** * @param board: A list of lists of character * @param words: A list of string * @return: A list of string */ public int[] dx = {1, 0, -1, 0}; //搜索方向 public int[] dy = {0, 1, 0, -1}; public void search(char[][] board, //在字典树上dfs查找 int x, int y, TrieNode root, List<String> results) { if (!root.children.containsKey(board[x][y])) { return; } TrieNode child = root.children.get(board[x][y]); if (child.word != null) { //如果访问到字典树叶子,将字符串压入result即可 if (!results.contains(child.word)) { results.add(child.word); } } char tmp = board[x][y]; board[x][y] = 0; // mark board[x][y] as used for (int i = 0; i < 4; i++) { //向四个方向dfs搜索 if (!isValid(board, x + dx[i], y + dy[i])) { continue; } search(board, x + dx[i], y + dy[i], child, results); } board[x][y] = tmp; // revert the mark } private boolean isValid(char[][] board, int x, int y) { //检测搜索位置合法 if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) { return false; } return board[x][y] != 0; } public List<String> wordSearchII(char[][] board, List<String> words) { List<String> results = new ArrayList<String>(); TrieTree tree = new TrieTree(new TrieNode()); for (String word : words){ tree.insert(word); } for (int i = 0; i < board.length; i++) { //遍历字母矩阵,将每个字母作为单词首字母开始搜索 for (int j = 0; j < board[i].length; j++) { search(board, i, j, tree.root, results); } } return results; } }
以上是关于Word Search II的主要内容,如果未能解决你的问题,请参考以下文章