[leetcode] 212.Word Search II

来源:互联网 发布:电脑桌面美化软件排行 编辑:程序博客网 时间:2024/04/28 02:30

题目:
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”].
题意:
给定一个二维的字符数组board,以及一系列字典中的单词,从board中找出所有的单词。从board中找单词只能从某个字符跳到它的相邻字符。相邻的意思是指其上下左右四个相邻的字符。
思路:

  1. 先将字典中的单词存入Trie树中。
  2. 以board的每个元素作为起点,查找有所有出现在Trie树中的单词。
  3. 对board采用DFS,并且回溯四个方向。
  4. 如果Trie树中某个单词已经被加入结果中,此时应该把Trie树中该单词对应的leaf标签去除,避免结果中该单词重复出现。比如单词“aaa”,可以从board[0][0]出发搜索出,也可以从board[0][1]出发搜索出,所以在第一次搜索出该单词后,需要在Trie树中将该单词的leaf标签去掉,避免从board[0][1]再次搜索出。
  5. 采用回溯的DFS,可以将当前board[i][j]的字符设为’*’,代表该字符在此次DFS中已经出现过,待回溯完,再将字符设回原来的值。
    以上。
    代码如下:
struct TrieNode {    char c;    bool isLeaf;    vector<TrieNode*> children;    TrieNode(char cc, bool leaf = false) :c(cc), isLeaf(leaf){ children.resize(26, NULL); }    TrieNode():c('~'),isLeaf(false){ children.resize(26); }};class Solution {public:    Solution() {        root = new TrieNode();    }    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {        if (board.empty() || words.empty())return vector<string>();        vector<string> result;        buildTree(words);        for (int i = 0; i < board.size(); i++)            for (int j = 0; j < board[0].size(); j++)                findWord(board, i, j, root, result, "");        return result;    }    void buildTree(vector<string>& words) {        for (auto s : words) {            if (s.empty())continue;            TrieNode* tmp = root;            for (auto c : s) {                if (tmp->children[c - 'a'] == NULL) {                    //cout << "build node " << c << endl;                    TrieNode* node = new TrieNode(c);                    tmp->children[c - 'a'] = node;                }                tmp = tmp->children[c - 'a'];            }            tmp->isLeaf = true;        }    }    void findWord(vector<vector<char>>& board, int i, int j, TrieNode* node, vector<string>& result, string res) {        if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] == '*')return;        char tmp = board[i][j];        res.push_back(tmp);        node = node->children[tmp - 'a'];        if (node == NULL) {            return;        }        if (node->isLeaf) {            node->isLeaf = false;            result.push_back(res);            //return;        }        board[i][j] = '*';        findWord(board, i - 1, j, node, result, res);        findWord(board, i + 1, j, node, result, res);        findWord(board, i, j - 1, node, result, res);        findWord(board, i, j + 1, node, result, res);        board[i][j] = tmp;    }private:    TrieNode* root;};
0 0