?LeetCode刷題實(shí)戰(zhàn)212:?jiǎn)卧~搜索 II
Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
題意
示例

輸入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
輸出:["eat","oath"]
提示:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] 是一個(gè)小寫英文字母
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] 由小寫英文字母組成
words 中的所有字符串互不相同
解題
public class Solution {
private TrieNode root = new TrieNode();
private int[] ro = {-1, 1, 0, 0};
private int[] co = {0, 0, -1, 1};
private void find(char[][] board, boolean[][] visited, int row, int col, TrieNode node, Set<String> founded) {
visited[row][col] = true;
TrieNode current = node.nexts[board[row][col]-'a'];
if (current.word != null) founded.add(current.word);
for(int i=0; i<4; i++) {
int nr = row + ro[i];
int nc = col + co[i];
if (nr < 0 || nr >= board.length || nc < 0 || nc >= board[nr].length || visited[nr][nc]) continue;
TrieNode next = current.nexts[board[nr][nc]-'a'];
if (next != null) find(board, visited, nr, nc, current, founded);
}
visited[row][col] = false;
}
public List<String> findWords(char[][] board, String[] words) {
Set<String> founded = new HashSet<>();
for(int i=0; i<words.length; i++) {
char[] wa = words[i].toCharArray();
TrieNode node = root;
for(int j=0; j<wa.length; j++) node = node.append(wa[j]);
node.word = words[i];
}
boolean[][] visited = new boolean[board.length][board[0].length];
for(int i=0; i<board.length; i++) {
for(int j=0; j<board[i].length; j++) {
if (root.nexts[board[i][j]-'a'] != null) find(board, visited, i, j, root, founded);
}
}
List<String> results = new ArrayList<>();
results.addAll(founded);
return results;
}
}
class TrieNode {
String word;
TrieNode[] nexts = new TrieNode[26];
TrieNode append(char ch) {
if (nexts[ch-'a'] != null) return nexts[ch-'a'];
nexts[ch-'a'] = new TrieNode();
return nexts[ch-'a'];
}
}
LeetCode1-200題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)201:數(shù)字范圍按位與
LeetCode刷題實(shí)戰(zhàn)202:快樂數(shù)
LeetCode刷題實(shí)戰(zhàn)203:移除鏈表元素
LeetCode刷題實(shí)戰(zhàn)204:計(jì)數(shù)質(zhì)數(shù)
LeetCode刷題實(shí)戰(zhàn)205:同構(gòu)字符串
LeetCode刷題實(shí)戰(zhàn)206:反轉(zhuǎn)鏈表
LeetCode刷題實(shí)戰(zhàn)207:課程表
LeetCode刷題實(shí)戰(zhàn)208:實(shí)現(xiàn) Trie (前綴樹)
LeetCode刷題實(shí)戰(zhàn)209:長(zhǎng)度最小的子數(shù)組
LeetCode刷題實(shí)戰(zhàn)210:課程表 II
LeetCode刷題實(shí)戰(zhàn)211:添加與搜索單詞
