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.
题目链接:https://leetcode.com/problems/word-search-ii/
题目分析:先按给定的单词建立Trie树,然后从矩阵中的每个单词的首字母开始深搜,深搜的要按照字典树中单词的方向,注意找到一个后不能直接return,因为可能存在某个单词是另一个单词的前缀。
击败了63%
public class Solution {
public static final int dx[] = {1, 0, -1, 0};
public static final int dy[] = {0, 1, 0, -1};
public boolean[][] vis;
class Trie {
boolean end;
String word;
Trie[] nxt;
public Trie() {
nxt = new Trie[26];
end = false;
word = "";
for (int i = 0; i < 26; i ++) {
nxt[i] = null;
}
}
public void Insert(Trie root, String str) {
int len = str.length();
Trie p = root;
for (int i = 0; i < len; i ++) {
int idx = str.charAt(i) - 'a';
if (p.nxt[idx] == null) {
p.nxt[idx] = new Trie();
}
p = p.nxt[idx];
}
p.end = true;
p.word = str;
}
}
public void DFS(int x, int y, int n, int m, Trie cur, boolean[][] vis, char[][] board, List<String> ans) {
if (cur == null) {
return;
}
if (cur.end) {
cur.end = false;
ans.add(cur.word);
}
for (int i = 0; i < 4; i ++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 0 && yy >= 0 && xx < n && yy < m && !vis[xx][yy]) {
int idx = board[xx][yy] - 'a';
if (cur.nxt[idx] != null) {
vis[xx][yy] = true;
DFS(xx, yy, n, m, cur.nxt[idx], vis, board, ans);
vis[xx][yy] = false;
}
}
}
return;
}
public List<String> findWords(char[][] board, String[] words) {
Trie root = new Trie();
for (int i = 0; i < words.length; i ++) {
root.Insert(root, words[i]);
}
List<String> ans = new ArrayList<>();
int n = board.length;
if (n == 0) {
return ans;
}
int m = board[0].length;
vis = new boolean[n][m];
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
int idx = board[i][j] - 'a';
if (root.nxt[idx] != null) {
vis[i][j] = true;
DFS(i, j, n, m, root.nxt[idx], vis, board, ans);
vis[i][j] = false;
}
}
}
// Collections.sort(ans, new Comparator() {
// @Override
// public int compare(Object o1, Object o2) {
// return ((String) o1).compareTo((String) o2);
// }
// });
return ans;
}
}

本文提供了一种解决LeetCode上单词搜索II问题的方法,通过构建Trie树并使用深度优先搜索策略来查找给定二维字符网格中存在的所有字典词汇。
999

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



