您的位置:首页 > 其它

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: