题目描述

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

链接:https://leetcode-cn.com/problems/word-search-ii

示例1
search1.jpg

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

解题思路

这道题与之前的单词搜索不一样,其涉及到多个单词搜索,并且在矩阵中有重合。不能直接用for循环照搬之前的方法,这里的主要思路是首先建立前缀树,然后for循环遍历矩阵直到找到第一个出现在前缀树的字母,然后再在前缀树依靠矩阵的四个方向里进行DFS:

  1. class Trie {
  2. public:
  3. map<char, Trie*> next;
  4. string word;
  5. Trie() {
  6. word = "";
  7. }
  8. void insert(string word) {
  9. Trie* node = this;
  10. for (auto ch: word) {
  11. if (node->next.count(ch) == 0) {
  12. node->next[ch] = new Trie();
  13. node = node->next[ch];
  14. }
  15. else {
  16. node = node->next[ch];
  17. }
  18. }
  19. node->word = word;
  20. }
  21. };
  22. class Solution {
  23. public:
  24. int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
  25. set<string> record;
  26. void search(vector<vector<char>>& board, Trie* node, int i, int j) {
  27. if (node->word != "") {
  28. record.insert(node->word);
  29. node->word = "";
  30. }
  31. if (i<0 || i>=board.size() || j<0 || j>=board[0].size() || board[i][j] == '#')
  32. return;
  33. if (node->next.count(board[i][j])) {
  34. char origin_ch = board[i][j];
  35. board[i][j] = '#';
  36. for (int k=0; k<4; k++) {
  37. int new_i=i+dir[k][0], new_j=j+dir[k][1];
  38. search(board, node->next[origin_ch], new_i, new_j);
  39. }
  40. board[i][j] = origin_ch;
  41. }
  42. }
  43. vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
  44. Trie* root = new Trie();
  45. for (auto str: words) {
  46. root->insert(str);
  47. }
  48. int count=0;
  49. for (int i=0; i<board.size(); i++) {
  50. for (int j=0; j<board[0].size(); j++) {
  51. if (record.size() == words.size())
  52. return words;
  53. search(board, root, i, j);
  54. }
  55. }
  56. return vector<string>(record.begin(), record.end());
  57. }
  58. };