0%

leetCode-212:Word Search II

问题描述

给定一个由字母构成的二维数组和一个单词列表,要求找出所有在二维数组中经过上下左右查找拼接而成的单词并且这个单词出现在单词列表中。查找过程中每个单词的每个字母仅能使用一次单元格,且每次仅能从一个单元格的上一个格子、下一个格子、左一个格子、右一个格子中进行查找。题目链接:**点我**

样例输入输出

输入:board = [[“o”,”a”,”a”,”n”],[“e”,”t”,”a”,”e”],[“i”,”h”,”k”,”r”],[“i”,”f”,”l”,”v”]], words = [“oath”,”pea”,”eat”,”rain”]

输出:[“eat”,”oath”]

输入:board = [[“a”,”b”],[“c”,”d”]], words = [“abcb”]

输出:[]

问题解法

用单词列表中的单词构建字典树,然后遍历二维数组,判断当前单元格是否存在字典树中,如果存在,则继续遍历,如果不存在,则结束此次遍历。对树的每个节点,判断是否是单词的最后一个字母,如果是,则放入结果集中。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class Solution
{
class Node
{
Node[] children;
char ch;
boolean isEnd;
String word;

public Node(char ch)
{
this.ch = ch;
children = new Node[26];
isEnd = false;
word = "";
}
}

public List<String> findWords(char[][] board, String[] words)
{
Node root = buildTree(words);
Set<String> result = new HashSet<>();
boolean[][] isUsed = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++)
{
for (int j = 0; j < board[0].length; j++)
{
find(board, i, j, root, result, isUsed);
}
}

return new ArrayList<>(result);
}

private void find(char[][] board, int i, int j, Node root, Set<String> result, boolean[][] isUsed)
{
if (root.isEnd)
{
result.add(root.word);
}

if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || isUsed[i][j])
{
return;
}

int index = board[i][j] - 'a';
if (root.children[index] == null)
{
return;
}

isUsed[i][j] = true;

find(board, i + 1, j, root.children[index], result, isUsed);
find(board, i - 1, j, root.children[index], result, isUsed);
find(board, i, j + 1, root.children[index], result, isUsed);
find(board, i, j - 1, root.children[index], result, isUsed);

isUsed[i][j] = false;
}

private Node buildTree(String[] words)
{
Node root = new Node('#');
for (String word : words)
{
Node current = root;
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
if (current.children[ch - 'a'] == null)
{
current.children[ch - 'a'] = new Node(ch);
}

current = current.children[ch - 'a'];
}

current.isEnd = true;
current.word = word;
}

return root;
}
}