题目
给定一个 m x n
二维字符网格 board
和一个单词(字符串)列表 words
, 返回所有二维网格上的单词 。
单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例 1:

1 2
| 输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] 输出:["eat","oath"]
|
示例 2:

1 2
| 输入:board = [["a","b"],["c","d"]], words = ["abcb"] 输出:[]
|
提示:
m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j]
是一个小写英文字母
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i]
由小写英文字母组成
words
中的所有字符串互不相同
题解
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
| class Solution {
Set<String> set = new HashSet<>(); char[][] board; int n, m; TrieNode root = new TrieNode(); int[][] dirs = new int[][] { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; boolean[][] vis = new boolean[15][15];
class TrieNode { String s; TrieNode[] tns = new TrieNode[26]; }
void insert(String s) { TrieNode p = root; for (int i = 0; i < s.length(); i++) { int u = s.charAt(i) - 'a'; if (p.tns[u] == null) p.tns[u] = new TrieNode(); p = p.tns[u]; } p.s = s; }
public List<String> findWords(char[][] _board, String[] words) { board = _board; m = board.length; n = board[0].length; for (String w : words) insert(w); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int u = board[i][j] - 'a'; if (root.tns[u] != null) { vis[i][j] = true; dfs(i, j, root.tns[u]); vis[i][j] = false; } } } List<String> ans = new ArrayList<>(); for (String s : set) ans.add(s); return ans; }
void dfs(int i, int j, TrieNode node) { if (node.s != null) set.add(node.s); for (int[] d : dirs) { int dx = i + d[0], dy = j + d[1]; if (dx < 0 || dx >= m || dy < 0 || dy >= n) continue; if (vis[dx][dy]) continue; int u = board[dx][dy] - 'a'; if (node.tns[u] != null) { vis[dx][dy] = true; dfs(dx, dy, node.tns[u]); vis[dx][dy] = false; } } } }
|