LeetCode 212. Word Search II

来源:互联网 发布:高瓴资本红杉资本知乎 编辑:程序博客网 时间:2024/04/28 03:01

212. Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[  ['o','a','a','n'],  ['e','t','a','e'],  ['i','h','k','r'],  ['i','f','l','v']]
Return ["eat","oath"].

Note:
You may assume that all inputs are consist of lowercase letters a-z.

/*思路: 跟79:Word Search类似,区别就是这一题给的是单词表,比较直接的方法是每个单词进行一次dfs搜索, 但是其时间复杂度很高, 有可能会超时;另一个方法就是利用字典树来做, 先将所有的单词添加到字典树中,然后从地图的每一个元素进行搜索, 搜索过程中如果其元素可以在字典树中找到, 那么就继续搜索下去, 并且如果搜索到某个结点的时候发现到这个结点构成了一个单词, 那么就将单词添加到结果集合中. */class Solution {  public:      struct Trie { //结点类型定义         Trie* child[26];        bool isWord;      };      vector<string> ans;//存放结果集合    int m, n;    void dfs(vector<vector<char>>& board, Trie *root, int x, int y, string word) {          if(!root) return;        word += board[x][y];        if(root->isWord){            ans.push_back(word);            root->isWord = false;        }        char c = board[x][y];        board[x][y] = '\0';//标记搜索过的点        //从上下左右四个方向进行搜索        if(x+1 < m && board[x+1][y] != '\0')            dfs(board, root->child[board[x+1][y]-'a'], x+1, y, word);        if(x-1 >= 0 && board[x-1][y] != '\0')            dfs(board, root->child[board[x-1][y]-'a'], x-1, y, word);        if(y+1 < n && board[x][y+1] != '\0')            dfs(board, root->child[board[x][y+1]-'a'], x, y+1, word);        if(y-1 >= 0 && board[x][y-1] != '\0')            dfs(board, root->child[board[x][y-1]-'a'], x, y-1, word);        board[x][y] = c;//搜索不成功取消标记    }      vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {          m = board.size();        n = board[0].size();        Trie *root = new Trie(), *node;        //对root结点进行初始化        for(int i = 0; i < 26; i++){            root->child[i] = NULL;        }        root->isWord = false;        //将所有的单词添加到字典树中        for(int i = 0; i < words.size(); i++){            node = root;            for(int j = 0; j < words[i].length(); j++){                if(!node->child[words[i][j]-'a'])                    node->child[words[i][j]-'a'] = new Trie();                node = node->child[words[i][j]-'a'];            }            node->isWord = true;        }        //从地图的每一个元素进行搜索        for(int i = 0; i < m; i++){            for(int j = 0; j < n; j++){                dfs(board, root->child[board[i][j]-'a'], i, j, "");            }        }        return ans;    }  };