Word Search II 解答
2015-10-14 09:02
393 查看
Question
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.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Solution
If the current candidate does not exist in all words' prefix, we can stop backtracking immediately. This can be done by using a trie structure.public class Solution { Set<String> result = new HashSet<String>(); public List<String> findWords(char[][] board, String[] words) { Trie trie = new Trie(); for (String word : words) trie.insert(word); int m = board.length, n = board[0].length; boolean[][] visited = new boolean[m] ; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { dfs(board, "", i, j, trie, visited); } } return new ArrayList<String>(result); } private void dfs(char[][] board, String prev, int startX, int startY, Trie trie, boolean[][] visited) { int m = board.length, n = board[0].length; if (startX < 0 || startX >= m || startY < 0 || startY >= n) return; if (visited[startX][startY]) return; String current = prev + board[startX][startY]; if (!trie.startsWith(current)) return; if (trie.search(current)) result.add(current); visited[startX][startY] = true; dfs(board, current, startX + 1, startY, trie, visited); dfs(board, current, startX - 1, startY, trie, visited); dfs(board, current, startX, startY + 1, trie, visited); dfs(board, current, startX, startY - 1, trie, visited); visited[startX][startY] = false; } }
Construct Trie
class TrieNode { public char value; public boolean isLeaf; public HashMap<Character, TrieNode> children; // Initialize your data structure here. public TrieNode(char c) { value = c; children = new HashMap<Character, TrieNode>(); } } class Trie { TrieNode root; public Trie() { root = new TrieNode('!'); } // Inserts a word into the trie. public void insert(String word) { char[] wordArray = word.toCharArray(); TrieNode currentNode = root; for (int i = 0; i < wordArray.length; i++) { char c = wordArray[i]; HashMap<Character, TrieNode> children = currentNode.children; TrieNode node; if (children.containsKey(c)) { node = children.get(c); } else { node = new TrieNode(c); children.put(c, node); } currentNode = node; if (i == wordArray.length - 1) currentNode.isLeaf = true; } } // Returns if the word is in the trie. public boolean search(String word) { TrieNode currentNode = root; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); HashMap<Character, TrieNode> children = currentNode.children; if (children.containsKey(c)) { TrieNode node = children.get(c); currentNode = node; // Need to check whether it's leaf node if (i == word.length() - 1 && !node.isLeaf) return false; } else { return false; } } return true; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode currentNode = root; for (int i = 0; i < prefix.length(); i++) { char c = prefix.charAt(i); HashMap<Character, TrieNode> children = currentNode.children; if (children.containsKey(c)) { TrieNode node = children.get(c); currentNode = node; } else { return false; } } return true; } }
相关文章推荐
- 错误:No resource found that matches the given name 'Theme.AppCompat.Light'解决方法
- Tomcat处理HTTP请求:Connector源码
- Tomcat中的Connector配备
- Tomcat 的三种(bio,nio.apr) 高级 Connector 运行模式
- git理解和使用
- Apache负载均衡+Tomcat集群
- Tomcat connector元素常用配置(最大连接数等)
- Spring MVC国际化
- packageinstaller之权限获取及展现
- 事务
- App应用之发布各广告平台版本
- 使用Java实现DNS域名解析的简单示例
- Arch Linux 环境下使用 Tomcat 6 搭建多站点、带SSL证书、高性能NIO/APR网站的配置详解
- Tomcat性能调优
- poj 1971 Parallelogram Counting 排序 + 计数
- CLRS 7.4快速排序分析
- 解决编码问题
- excel选择符合条件的行
- 两个队列实现一个栈
- Linux下高并发socket最大连接数所受的各种限制