Description
Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Examples
Example 1:
Input: board = [[“o”,“a”,“a”,“n”],[“e”,“t”,“a”,“e”],[“i”,“h”,“k”,“r”],[“i”,“f”,“l”,“v”]], words = [“oath”,“pea”,“eat”,“rain”] Output: [“eat”,“oath”]
Example 2:
Input: board = [[“a”,“b”],[“c”,“d”]], words = [“abcb”] Output: []
Constraints:
m == board.length n == board[i].length 1 <= m, n <= 12 board[i][j] is a lowercase English letter. 1 <= words.length <= 3 * 104 1 <= words[i].length <= 10 words[i] consists of lowercase English letters. All the strings of words are unique.
思路
首先这个数据量是肯定需要剪枝的,剪枝策略可以通过前缀树实现,适用于share相同前缀的各个情况,不用每次都从头开始计算。 所以步骤就是先对要检测的String数组构建前缀树,再用dfs对这棵树进行搜索,得到最后的答案序列。
思路没有什么需要深究的地方,有了想法之后,直接写就行了,也没有特别的细节,但我这份的运行速度特别慢,应该里面还有一些可以优化的地方,下次做的时候再考虑一下。
代码
class TrieNode {
char ch;
String str;
TrieNode[] next;
public TrieNode(char c){
this.ch = c;
next = new TrieNode[26];
str = null;
}
}
class Solution {
List<String> answer = new ArrayList<>();
public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode('$');
for (String word: words) {
char[] chars = word.toCharArray();
TrieNode tmp = root;
for (char ch: chars) {
if (tmp.next[ch - 'a'] == null) {
TrieNode newNode = new TrieNode(ch);
tmp.next[ch - 'a'] = newNode;
}
tmp = tmp.next[ch - 'a'];
}
tmp.str = word;
}
return root;
}
public void dfs_visit(char[][] board, TrieNode node, int x, int y) {
if (x < 0 || x >= board.length || y < 0 || y >= board[x].length)
return;
if (node == null || board[x][y] != node.ch)
return;
if (node.str != null) {
answer.add(node.str);
node.str = null;
}
board[x][y] = '#';
for (TrieNode next: node.next) {
dfs_visit(board, next, x + 1, y);
dfs_visit(board, next, x - 1, y);
dfs_visit(board, next, x, y + 1);
dfs_visit(board, next, x, y - 1);
}
board[x][y] = node.ch;
}
public List<String> findWords(char[][] board, String[] words) {
TrieNode root = buildTrie(words);
for (TrieNode starter: root.next) {
if (starter == null)
continue;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == starter.ch)
dfs_visit(board, starter, i, j);
}
}
}
return answer;
}
}
|