前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 212 Word Search II 字典树 + 回溯

Leetcode 212 Word Search II 字典树 + 回溯

作者头像
triplebee
发布2018-01-12 14:44:18
4910
发布2018-01-12 14:44:18
举报

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 =

代码语言:javascript
复制
[
  ['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.

给一个矩阵,可以从任意一个位置开始,沿水平或垂直方向取连续字符组成字符串,问给定的字符串数组中有多少字符串可以从这个矩阵中生成。

直接套用之前trie的代码。

枚举每一个位置为起点进行dfs,dfs向四个方向搜索,如果当前位置的串不为树中某个词的前缀,则返回,否则看当前串是否为一个存在的单词并继续搜索。

需要注意用一个map维护出现过的单词,避免相同词重复加入结果容器。

同一个位置的字符在一个单词中只能使用一次,因此需要将搜索过的位置置为其他不为字母的字符,并在回溯时调整回来。

代码语言:javascript
复制
class node    
{    
public:    
    int flag;    
    node* next[26];    
    node(int x = 0)    
    {    
        flag = x;    
        memset(next, 0, sizeof(next));    
    }    
};    
class WordDictionary {  
public:  
    node* root;  
    /** Initialize your data structure here. */  
    WordDictionary() {  
        root = new node();  
    }  
    /** Adds a word into the data structure. */  
    void addWord(string word) {  
        //cout<<word<<endl;
        node* p = root;    
        for(int i = 0; i < word.size(); i++)    
        {    
            if(!p->next[word[i] - 'a']) p->next[word[i] - 'a'] = new node();    
            p = p->next[word[i] - 'a'];    
        }    
        p->flag = 1;   
    }
    /** Returns if the word is in the trie. */  
    bool search(string word)   
    {  
        node* p = root;  
        for(int i = 0; i < word.size(); i++)  
        {  
            if(!p->next[word[i] - 'a']) return false;  
            p = p->next[word[i] - 'a'];  
        }  
        return p->flag == 1;  
    }  
    /** Returns if there is any word in the trie that starts with the given prefix. */  
    bool startsWith(string prefix)   
    {  
        node* p = root;  
        for(int i = 0; i < prefix.size(); i++)  
        {  
            if(!p->next[prefix[i] - 'a']) return false;  
            p = p->next[prefix[i] - 'a'];  
        }  
        return true;  
    }  
};  
class Solution {
public:
    WordDictionary tree;
    unordered_map<string, bool> mp;
    void dfs(vector<string> &res, vector<vector<char>>& board, int i,int j, string now)
    {
        if(board[i][j] == ' ') return ;
        now += board[i][j];
        if(!tree.startsWith(now)) return ;
        if(tree.search(now) && !mp[now]) 
        {
            mp[now] = true;
            res.push_back(now);
        }
        char temp = board[i][j];
        board[i][j] = ' ';
        if(i < board.size() - 1) dfs(res, board, i + 1, j, now);
        if(i > 0) dfs(res, board, i - 1, j, now);
        if(j < board[0].size() - 1) dfs(res, board, i, j + 1, now);
        if(j > 0) dfs(res, board, i, j - 1, now);
        board[i][j] = temp;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> res;
        int m = board.size();
        if(m == 0) return res;
        int n = board[0].size();
        for(int i = 0; i < words.size(); i++) tree.addWord(words[i]);
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                string temp;
                dfs(res, board, i, j, temp);
            }
        }
        return res;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-03-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档