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"].
public class Solution {
Set<String> res = 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;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
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 str, int x,
int y, Trie trie) {
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length)
return;
if (visited[x][y])
return;
str += board[x][y];
if (!trie.startsWith(str))
return;
if (trie.search(str)) {
res.add(str);
}
visited[x][y] = true;
dfs(board, visited, str, x - 1, y, trie);
dfs(board, visited, str, x + 1, y, trie);
dfs(board, visited, str, x, y - 1, trie);
dfs(board, visited, str, x, y + 1, trie);
visited[x][y] = false;
}
}
class TrieNode {
private TrieNode[] nodes;
private boolean end;
public TrieNode() {
int size = 26;
nodes = new TrieNode[size];
end = false;
}
public void insert(char[] chars, int start) {
if (start == chars.length) {
end = true;
return;
}
int idx = chars[start] - 'a';
TrieNode node = nodes[idx];
if (node != null) {
node.insert(chars, start + 1);
} else {
node = new TrieNode();
nodes[chars[start] - 'a'] = node;
node.insert(chars, start + 1);
}
}
public boolean search(char[] chars, int start) {
if (start == chars.length) {
return end;
}
char c = chars[start];
TrieNode node = nodes[c - 'a'];
if (node == null) {
return false;
}
return node.search(chars, start + 1);
}
public boolean startWith(char[] chars, int start) {
if (start == chars.length) {
return true;
}
char c = chars[start];
TrieNode node = nodes[c - 'a'];
if (node == null) {
return false;
}
return node.startWith(chars, start + 1);
}
}
class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
root.insert(word.toCharArray(), 0);
}
// Returns if the word is in the trie.
public boolean search(String word) {
return root.search(word.toCharArray(), 0);
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
return root.startWith(prefix.toCharArray(), 0);
}
}
本文介绍了一种算法,用于在给定的二维棋盘上查找所有可能的单词,每个单词由相邻的字母组成,且同一字母不能重复使用。

被折叠的 条评论
为什么被折叠?



