思路
dfs+hashmap/trie。
【hashmap版本】首先生成一个存前缀和单词的hashmap用来存一个前缀是否为一个单词,假设一个字符串已经是单词(true)了就不要更新成前缀(false)了。
接下来在棋盘上4个方向dfs,由于一个单词中一个位置只能使用一次,于是需要使用一个visit来记录是否已经用过。如果当前字符串不在hashmap中就直接结束,否则如果当前字符串是一个单词,将其加入结果中并且继续搜索【因为可能该单词同时为另一个单词的前缀】,如果不是单词就继续搜索(不加入结果)
复杂度
时
间
复
杂
度
O
(
l
e
n
∗
n
∗
m
∗
4
l
)
:
l
e
n
为
答
案
个
数
,
l
为
单
词
最
大
长
度
时间复杂度O(len*n*m*4^l): len为答案个数,l为单词最大长度
时间复杂度O(len∗n∗m∗4l):len为答案个数,l为单词最大长度
空
间
复
杂
度
O
(
l
e
n
∗
l
+
n
∗
m
)
空间复杂度O(len*l + n*m)
空间复杂度O(len∗l+n∗m)
代码
class Solution {
public List<String> findWords(char[][] board, String[] words) {
// edge cases
if (board.length == 0 || board[0].length == 0 || words.length == 0) {
return new ArrayList<>();
}
int n = board.length, m = board[0].length;
HashMap<String, Boolean> prefixIsWord = getPrefixWord(words);
Set<String> wordSet = new HashSet<>();
boolean[][] visit = new boolean[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
visit[i][j] = true;
dfs(i, j, board, visit, String.valueOf(board[i][j]), wordSet, prefixIsWord);
visit[i][j] = false;
}
}
return new ArrayList<String>(wordSet);
}
private HashMap<String, Boolean> getPrefixWord(String[] words) {
HashMap<String, Boolean> res = new HashMap<>();
for (String s : words) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length() - 1; i++) {
sb.append(s.charAt(i));
if (!res.containsKey(sb.toString())) {
res.put(sb.toString(), false);
}
}
res.put(s, true);
}
return res;
}
private void dfs(int x, int y, char[][] board, boolean[][] visit,
String cur,
Set<String> wordSet,
Map<String, Boolean> isPrefixWord) {
if (!isPrefixWord.containsKey(cur)) {
return;
}
if (isPrefixWord.get(cur)) {
wordSet.add(cur);
}
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (!onBoard(nx, ny, board.length, board[0].length) || visit[nx][ny]) {
continue;
}
visit[nx][ny] = true;
dfs(nx, ny, board, visit, cur + board[nx][ny], wordSet, isPrefixWord);
visit[nx][ny] = false;
}
}
private boolean onBoard(int x, int y, int n, int m) {
return (0 <= x && x < n && 0 <= y && y < m);
}
}