ID | Title | Difficulty | |
---|---|---|---|
Loading... |
212. Word Search II
Hard
LeetCode
Array, String, Backtracking, Trie, Matrix
Problem
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.
Example 1:
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Example 2:
Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
Code
class Solution {
class Node{
Node[] children;
boolean isWord;
String word;
public Node(){
children = new Node[26];
isWord = false;
word = "";
}
}
Node root;
public List<String> findWords(char[][] board, String[] words) {
root = new Node();
List<String> res = new ArrayList<>();
for(String str : words){
build(str);
}
int m = board.length;
int n = board[0].length;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int index = board[i][j] - 'a';
if(root.children[index] != null){
Node node = root;
dfs(board, i, j, res, node);
}
}
}
return res;
}
private void dfs(char[][] board, int i, int j, List<String> res, Node node) {
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) return;
char c = board[i][j];
if(c == '#') return;
if(node.children[c - 'a'] == null) return;
if(node.children[c - 'a'].isWord){
res.add(node.children[c - 'a'].word);
node.children[c - 'a'].isWord = false;
}
board[i][j] = '#';
dfs(board, i + 1, j, res, node.children[c - 'a']);
dfs(board, i - 1, j, res, node.children[c - 'a']);
dfs(board, i, j + 1, res, node.children[c - 'a']);
dfs(board, i, j - 1, res, node.children[c - 'a']);
board[i][j] = c;
}
private void build(String s){
Node node = root;
for(int i = 0; i < s.length(); i++){
int index = s.charAt(i) - 'a';
if(node.children[index] == null){
node.children[index] = new Node();
}
node = node.children[index];
}
node.isWord = true;
node.word = s;
}
}
按 <- 键看上一题!
211. Design Add and Search Words Data Structure
按 -> 键看下一题!
213. House Robber II