import java.util.*;
class ListNode {
// 结尾标记,对应words中的第i个字符串,若为-1则代表不存在字符串;
int flag;
// 可以考虑更换成ListNode[26],并且让flag=-2表示存在子节点
Map<Character, ListNode> next;
public ListNode() {
flag = -1;
next = new HashMap<>();
}
}
class Solution {
ListNode head;
char[][] board;
List<String> ans;
String[] words;
static int[][] direction = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
int m;
int n;
public List<String> findWords(char[][] board, String[] words) {
ans = new ArrayList<>();
head = new ListNode();
this.words = words;
int len = words.length;
m = board.length;
n = board[0].length;
this.board = board;
for (int i = 0; i < len; i++) {
int len2 = words[i].length();
ListNode temp = head;
for (int j = 0; j < len2; j++) {
ListNode next;
if (!temp.next.containsKey(words[i].charAt(j))) {
next = new ListNode();
temp.next.put(words[i].charAt(j), next);
} else {
next = temp.next.get(words[i].charAt(j));
}
temp = next;
}
temp.flag = i;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(i, j, head);
}
}
return ans;
}
void dfs(int i, int j, ListNode temp) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] == '#' || !temp.next.containsKey(board[i][j])) {
return;
}
temp = temp.next.get(board[i][j]);
char bef = board[i][j];
board[i][j] = '#';
if (temp.flag >= 0) {
ans.add(words[temp.flag]);
// 避免添加重复答案,取消结尾标记
temp.flag = -1;
}
for (int[] dir : direction) {
dfs(i + dir[0], j + dir[1], temp);
}
// 回溯
board[i][j] = bef;
}
}
Leetcode_212_单词搜索二_前缀树
最新推荐文章于 2025-05-18 01:00:00 发布
该博客介绍了一个Java实现的解决方案,用于在一个二维字符矩阵中查找给定单词列表中的单词。它利用了深度优先搜索(DFS)策略,并通过一个链表结构维护字母之间的连接。在搜索过程中,遇到匹配的单词会将其添加到结果列表中,并对已访问过的单元格进行标记以避免重复。最后,返回找到的所有单词。

393

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



