[leetcode] 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”].
题意:
给定一个二维的字符数组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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值