[leetcode] 212. Word Search II 解题报告

题目链接: https://leetcode.com/problems/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.


思路: 一种比较直观的方法是每个单词进行一次DFS搜索, 但是这样速度比较慢, 其时间复杂度最坏会达到O(m^2 * n^2 *k), 即每个单词都会从地图的每一个元素开始搜索, 如果单词足够长且每次都搜索完整个地图, 那么时间复杂度就是最坏了. 这种方法肯定是不能完成大量数据的. 

更好的方法是利用字典树Trie来做, 就是将要搜索的单词先添加到字典树中, 然后从地图board的每一个元素搜索, 如果往上下左右搜索的时候其元素可以在字典树中找到, 那么就继续搜索下去, 并且如果搜索到某个结点的时候发现到这个结点构成了一个单词, 那么就将单词添加到结果集合中. 如果在字典树中无法找到这个元素, 那么就结束当前分支的搜索.

另外还需要标记搜索过的点, 可以再开一个二维数组来标记, 也可以改变其值, 搜索完之后再改回来, 这种方法的好处是不用额外的空间, 速度也会更快.

代码如下:

class Solution {
public:
    struct Trie
    {
        vector child;
        bool isWord;
        Trie(): child(vector(26, NULL)), isWord(false){}
    };
    
    void DFS(vector>& board, Trie *root, int x, int y, string str)
    {
        int row = board.size(), col = board[0].size();
        if(!root || board[x][y] == '#') return;
        str += board[x][y];
        if(root->isWord)
        {
            ans.push_back(str);
            root->isWord = false;
        }
        char ch = board[x][y];
        board[x][y] = '#';
        if(x+1 < row) DFS(board, root->child[board[x+1][y]-'a'], x+1, y, str);
        if(x-1 >= 0) DFS(board, root->child[board[x-1][y]-'a'], x-1, y, str);
        if(y+1 < col) DFS(board, root->child[board[x][y+1]-'a'], x, y+1, str);
        if(y-1 >= 0) DFS(board, root->child[board[x][y-1]-'a'], x, y-1, str);
        board[x][y] = ch;
    }
    
    vector findWords(vector>& board, vector& words) {
        if(board.size() ==0) return {};
        Trie *root = new Trie(), *node;
        for(auto str: words)
        {
            node = root;
            for(auto ch: str)
            {
                if(!node->child[ch-'a']) node->child[ch-'a'] = new Trie();
                node = node->child[ch-'a'];
            }
            node->isWord = true;
        }
        for(int i = 0; i < board.size(); i++)
            for(int j =0; j < board[0].size(); j++)
                DFS(board, root->child[board[i][j]-'a'], i, j, "");
        return ans;
    }
private:
    vector ans;
};


你可能感兴趣的:(leetcode,DFS,trie)