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
.
思路:这题直接暴力用backtracking, 题目不求重复,board: [["a"]], words: ["a","a"] 要求只返回["a"],也就是list里面有了,就不要再加入了。
hint提示用了trie。思路就是对于矩阵里面的每一个点为起点开始搜索,如果startwith trie,那么就开始搜索,search到了就加到hashset里面,最后返回。因为trie的搜索很快,所以不会超时。其实传递trietree进去,就已经相当于把所有的word全部传进去了,那么对于每个 x,y,那么只需要在这个点展开,搜索所有可能的string就可以了。参数传递不需要用word,只需要用trietree,因为是搜所有可能的word;注意去重复;
Time: ( m * n * 4 * 3 ^ (L - 1) )
Space: 26 * N
class Solution {
class TrieNode {
public TrieNode[] children;
public boolean isword;
public String word;
public TrieNode() {
this.children = new TrieNode[26];
this.isword = false;
this.word = null;
}
}
class Trie {
public TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public void insertWord(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.isword = true;
cur.word = word;
}
}
public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<String>();
if(board == null || board.length == 0 || board[0].length == 0) {
return res;
}
Trie trie = new Trie();
for(String word: words) {
trie.insertWord(word);
}
int m = board.length;
int n = board[0].length;
HashSet<String> set = new HashSet<>();
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
boolean[][] visited = new boolean[m][n];
dfs(board, i, j, trie.root, res, set, visited);
}
}
return res;
}
private int[][] dirs = {{0,-1},{0,1},{1,0},{-1,0}};
private void dfs(char[][] board, int x, int y, TrieNode cur, List<String> res, HashSet<String> set,
boolean[][] visited) {
if(x < 0 || x >= board.length || y < 0 || y >= board[0].length || visited[x][y]) {
return;
}
char c = board[x][y];
if(cur.children[c - 'a'] == null) {
return;
}
cur = cur.children[c - 'a'];
if(cur.isword && !set.contains(cur.word)) {
set.add(cur.word);
res.add(cur.word);
}
visited[x][y] = true;
for(int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
dfs(board, nx, ny, cur, res, set, visited);
}
visited[x][y] = false;
}
}