Leetcode 212. 单词搜索 II

字典树+回溯
使用unordered_map去重

class Solution {
public:
    int tree[10000][30],ed[10000],tot,vis[15][15],n,m;
    vector<string>res;
    unordered_map<int,string>mp;
    unordered_map<int,int>mp2;
    void insert(string s){
        int root=0;
        for(auto tmp:s){
            if(tree[root][tmp-'a']==0)
                tree[root][tmp-'a']=++tot;
            root=tree[root][tmp-'a'];
        }
        ed[root]=1;
        mp[root]=s;
    }
    vector<pair<int,int>>pa={{1,0},{-1,0},{0,1},{0,-1}};
    void dfs(int root,int x,int y,vector<vector<char>>& board){
        //cout<<root<< x<< y<<endl;
        vis[x][y]=1;
        root=tree[root][board[x][y]-'a'];
        if(ed[root]==1 && mp2[root]==0)
            res.push_back(mp[root]),mp2[root]=1;
        //cout<<root<<endl;    
        for(auto tmp:pa){
            int tox=tmp.first+x;
            int toy=tmp.second+y;
            //cout<<tox<<toy<<endl;
        if(tox>=0 && tox<n && toy<m && toy>=0 && vis[tox][toy]==0 && tree[root][board[tox][toy]-'a'])        {
             //cout<<tox<<toy<<endl;
             dfs(root,tox,toy,board);
        }
            //cout<<10086<<endl;
        }
        vis[x][y]=0;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        memset(tree,0,sizeof(tree));
        memset(ed,0,sizeof(ed));
        memset(vis,0,sizeof(vis));
        tot=0;
        m=board[0].size();
        n=board.size();
        for(auto i:words)
            insert(i);
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                if(tree[0][board[i][j]-'a'])
                dfs(0,i,j,board);
            }
        }    
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值