212. 單詞搜尋 II (JAVA)
阿新 • • 發佈:2020-08-03
給定一個二維網格board和一個字典中的單詞列表 words,找出所有同時在二維網格和字典中出現的單詞。
單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內的字母在一個單詞中不允許被重複使用。
示例:
輸入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
輸出:["eat","oath"]
說明:
提示:
你需要優化回溯演算法以通過更大資料量的測試。你能否早點停止回溯?
如果當前單詞不存在於所有單詞的字首中,則可以立即停止回溯。什麼樣的資料結構可以有效地執行這樣的操作?散列表是否可行?為什麼? 字首樹如何?如果你想學習如何實現一個基本的字首樹,請先檢視這個問題: 實現Trie(字首樹)。
思路:字首樹+回溯
class Solution { public List<String> findWords(char[][] board, String[] words) { WordTrie trie = new WordTrie(); TreeNode root= trie.root; Set<String> result = new HashSet<>(); //使用set防止答案中有重複單詞 boolean[][] visited = new boolean[board.length][board[0].length]; for(int i = 0; i < words.length; i++){ trie.insert(words[i]); } for(int i = 0; i < board.length; i++){for(int j = 0; j < board[0].length; j++){ find(board,i,j,result,root,visited); } } //System.out.print(result); return new LinkedList<String>(result); } public void find(char[][] board, int m, int n, Set<String> result, TreeNode currentNode, boolean[][] visited) { if(m >= board.length || m < 0 || n >= board[0].length || n < 0 || visited[m][n]) { return; } currentNode = currentNode.child[board[m][n]-'a']; if( currentNode ==null){ //沒有找到,回溯 return; } if(currentNode.isEnd){ //找到了一個單詞 result.add(currentNode.value); } visited[m][n] = true; //繼續尋找後續單詞。比如找到了"ad",可能還會有"advertisement" find(board,m+1, n, result, currentNode,visited); find(board,m-1, n, result, currentNode,visited); find(board,m, n+1, result, currentNode,visited); find(board,m, n-1, result, currentNode,visited); visited[m][n]=false; //最後回溯 } public class WordTrie { public TreeNode root; private TreeNode current; /** Initialize your data structure here. */ public WordTrie() { root = new TreeNode(); } /** Inserts a word into the trie. */ public void insert(String word) { TreeNode current = root; for(int i = 0; i < word.length(); i++){ if(current.child[word.charAt(i)-'a'] == null) { current.child[word.charAt(i)-'a'] = new TreeNode(); } current = current.child[word.charAt(i)-'a']; } current.isEnd = true; current.value = word; } } public class TreeNode { public String value; public TreeNode[] child; public boolean isEnd; public TreeNode() { this.child = new TreeNode[26]; this.isEnd = false; } } }