1. 程式人生 > >Leetcode 212.單詞搜尋II

Leetcode 212.單詞搜尋II

單詞搜尋II

給定一個二維網格 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"]

說明:
你可以假設所有輸入都由小寫字母 a-z 組成。

提示:

  • 你需要優化回溯演算法以通過更大資料量的測試。你能否早點停止回溯?
  • 如果當前單詞不存在於所有單詞的字首中,則可以立即停止回溯。什麼樣的資料結構可以有效地執行這樣的操作?散列表是否可行?為什麼? 字首樹如何?如果你想學習如何實現一個基本的字首樹,請先檢視這個問題: 實現Trie(字首樹)

方法:字首樹+深度優先搜尋。

 

 1 import java.util.ArrayList;
 2 import
java.util.HashSet; 3 import java.util.List; 4 import java.util.Set; 5 6 public class Solution { 7 private TrieNode root = new TrieNode(); 8 private int[] ro = {-1, 1, 0, 0}; 9 private int[] co = {0, 0, -1, 1}; 10 private void find(char[][] board, boolean[][] visited, int row, int
col, TrieNode node, Set<String> founded) { 11 visited[row][col] = true; 12 TrieNode current = node.nexts[board[row][col]-'a']; 13 if (current.word != null) founded.add(current.word); 14 for(int i=0; i<4; i++) { 15 int nr = row + ro[i]; 16 int nc = col + co[i]; 17 if (nr < 0 || nr >= board.length || nc < 0 || nc >= board[nr].length || visited[nr][nc]) continue; 18 TrieNode next = current.nexts[board[nr][nc]-'a']; 19 if (next != null) find(board, visited, nr, nc, current, founded); 20 } 21 visited[row][col] = false; 22 } 23 public List<String> findWords(char[][] board, String[] words) { 24 Set<String> founded = new HashSet<>(); 25 for(int i=0; i<words.length; i++) { 26 char[] wa = words[i].toCharArray(); 27 TrieNode node = root; 28 for(int j=0; j<wa.length; j++) node = node.append(wa[j]); 29 node.word = words[i]; 30 } 31 boolean[][] visited = new boolean[board.length][board[0].length]; 32 for(int i=0; i<board.length; i++) { 33 for(int j=0; j<board[i].length; j++) { 34 if (root.nexts[board[i][j]-'a'] != null) find(board, visited, i, j, root, founded); 35 } 36 } 37 List<String> results = new ArrayList<>(); 38 results.addAll(founded); 39 return results; 40 } 41 } 42 class TrieNode { 43 String word; 44 TrieNode[] nexts = new TrieNode[26]; 45 TrieNode append(char ch) { 46 if (nexts[ch-'a'] != null) return nexts[ch-'a']; 47 nexts[ch-'a'] = new TrieNode(); 48 return nexts[ch-'a']; 49 } 50 }

 

] = new TrieNode(); return nexts[ch-'a']; }}