LeetCode Word Search II DFS+Trie树
2015-11-06 13:04
274 查看
思路:
参考DISCUSS,使用Trie树加快dfs的搜索速度。
java code:
参考DISCUSS,使用Trie树加快dfs的搜索速度。
java code:
public class Solution { //construct a Trie to speed up search process class TrieNode { // Initialize your data structure here. public boolean isWord = false; public TrieNode[] children = new TrieNode[26]; public TrieNode() { } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { TrieNode cur = root; for(int i = 0; i < word.length(); ++i) { char c = word.charAt(i); if(cur.children[c - 'a'] == null) { cur.children[c - 'a'] = new TrieNode(); } cur = cur.children[c - 'a']; } cur.isWord = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode cur = root; for(int i = 0; i < word.length(); ++i) { char c = word.charAt(i); if(cur.children[c - 'a'] == null) return false; cur = cur.children[c - 'a']; } return cur.isWord; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode cur = root; for(int i = 0; i < prefix.length(); ++i) { char c = prefix.charAt(i); if(cur.children[c - 'a'] == null) return false; cur = cur.children[c - 'a']; } return true; } } Set<String> res = new HashSet<String>(); public List<String> findWords(char[][] board, String[] words) { //construct a Trie Trie trie = new Trie(); //init Tire for(int i = 0; i < words.length; ++i) { trie.insert(words[i]); } int m = board.length; int n = board[0].length; boolean[][] visited = new boolean[m] ; //start search from every character for(int i = 0; i < m; ++i) { for(int j = 0; j < n; ++j) { dfs(board, visited, "", i, j, trie); } } return new ArrayList<String>(res); } public void dfs(char[][] board, boolean[][] visited, String curStr, int i, int j, Trie trie) { if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) return; if(visited[i][j] == true) return; curStr += board[i][j]; //if Trie doestn't have curStr, it must not have the word which start with curStr, so pass if(!trie.startsWith(curStr)) return; if(trie.search(curStr)) { res.add(curStr); } visited[i][j] = true; dfs(board, visited, curStr, i + 1, j, trie); dfs(board, visited, curStr, i - 1, j, trie); dfs(board, visited, curStr, i, j + 1, trie); dfs(board, visited, curStr, i, j - 1, trie); visited[i][j] = false; } }
相关文章推荐
- ExtJS 性能优化注意要点
- 动态改变Font(字体)
- ListView,gallery与内部控件事件冲突以及EditText回退键和回车键失效
- 关于inflate的第3个参数
- Combinations
- (解题报告)HDU1001---Sum problem
- Linux查看当前登录用户并踢出用户
- VS2008中设置字体大小和添加显示行号
- Ubuntu 入门 Lession 02.文本模式下指令的下达
- 【Android实战】Bundle传递自定义Object的ArrayList
- eclipes+tomcat+spingmvc 发布到阿里云服务器mysql遇到问题
- xp安装教程
- hdu2084数塔(动态规划)
- Android Fragment 真正的完全解析(上)
- iOS每日一读官方文档01
- 方法覆盖(override)”的要点
- js、jquery常用
- CF 593D
- window.name==window['name']
- 对话 UNIX: 探察管道