[leetcde 212, Hard] Word Search II

本文介绍了一种使用字典树(Trie)数据结构和深度优先搜索(DFS)算法相结合的方法来解决在一个二维字母板上查找给定单词列表中的所有单词的问题。文章提供了详细的C++实现代码,包括字典树的构建、插入、查找以及单词搜索算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem:

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"].

Analysis:


Solutions:

C++:

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
        mp_node.resize(26, NULL);
        mb_is_word = false;
    }
    
    vector<TrieNode *> mp_node;
    bool mb_is_word;
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string s) {
        TrieNode *p_curr = root;
        for(int i = 0; i < s.size(); ++i) {
            if(p_curr->mp_node[s[i] - 'a'] == NULL)
                p_curr->mp_node[s[i] - 'a'] = new TrieNode();
            
            p_curr = p_curr->mp_node[s[i] - 'a'];
        }
        p_curr->mb_is_word = true;
    }

    // Returns if the word is in the trie.
    bool search(string key) {
        TrieNode *p_curr = root;
        for(int i = 0; i < key.size(); ++i) {
            if(p_curr->mp_node[key[i] - 'a'] == NULL)
                return false;

            p_curr = p_curr->mp_node[key[i] - 'a'];
        }

        return (p_curr->mb_is_word ? true : false);
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode *p_curr = root;
        for(int i = 0; i < prefix.size(); ++i) {
            if(p_curr->mp_node[prefix[i] - 'a'] == NULL)
                return false;

            p_curr = p_curr->mp_node[prefix[i] - 'a'];
        }

        return true;
    }

private:
    TrieNode* root;
};

    void dfs(vector<vector<char> >& board, vector<vector<bool> >& visited, string str, int x, int y, vector<string>& found, Trie& trie)
    {
        if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || visited[x][y])
            return;
        
        str.push_back(board[x][y]);
        if(!trie.startsWith(str))
            return;
            
        if(trie.search(str) && find(found.begin(), found.end(), str) == found.end())
            found.push_back(str);
            
        visited[x][y] = true;
        dfs(board, visited, str, x - 1, y, found, trie);
        dfs(board, visited, str, x, y - 1, found, trie);
        dfs(board, visited, str, x + 1, y, found, trie);
        dfs(board, visited, str, x, y + 1, found, trie);
        visited[x][y] = false;
    }
    
    vector<string> findWords(vector<vector<char> >& board, vector<string>& words) {
        vector<string> found;
        if(board.empty() || words.empty())
            return found;

        Trie trie;
        for(int i = 0; i < words.size(); ++i)
            trie.insert(words[i]);
        
        int row = board.size();
        int col = board[0].size();
        vector<vector<bool> > visited(row, vector<bool>(col, false));
        for(int i = 0; i < board.size(); ++i) {
            for(int j = 0; j < board[0].size(); ++j)
                dfs(board, visited, "", i, j, found, trie);
        }

        return found;
    }
Java:


Python:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值