给出一个2D板和字典中的单词列表,找到棋盘上的所有单词。每个单词必须由顺序相邻单元格的字母构成。不能重复使用

217 篇文章 0 订阅
174 篇文章 2 订阅

本题源自leetcode   212

-----------------------------------------------------------------------

思路:

构造一个Trie单词查找树。然后用递归遍历棋盘。找到所有的单词。

代码:

   class Trie{
    public:
        int idx;
        bool leaf;
        Trie* children[26];
        Trie(){
            this->idx = 0;  //如果当前节点是结尾,idx 是这个字符串在字典中的下标
            this->leaf = false;   //表示是否是一个字符串的结尾
            fill_n(this->children,26,nullptr);  //指向其从a-z的开始子串的指针。
        }    
    };
public:
    void insertWords(Trie* root,vector<string>& words,int idx){
        int len = words[idx].size();
        int i = 0;
        while(i < len){
            if(root->children[words[idx][i] - 'a'] == NULL)
                root->children[words[idx][i] - 'a'] = new Trie();
            root = root->children[words[idx][i] - 'a'];
            i++;
        }
        root->leaf = true;
        root->idx = idx;
    }
    Trie* buildTrie(vector<string>& words){
        Trie* root = new Trie();
        for(int i = 0; i < words.size(); i++){
            insertWords(root,words,i);
        }
        return root;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> res;
        int row = board.size();
        if(row == 0)
            return res;
        int col = board[0].size();
        if(col == 0)
            return res;
        int n = words.size();
        if(n == 0)
            return res;
        
        Trie* root = buildTrie(words);
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col && n > res.size(); j++){
                dfs(board,words,res,root,i,j,row,col);
            }
        }
        return res;
    }
    void dfs(vector<vector<char>>& board,vector<string>& words,vector<string>& res,Trie* root,int i,int j,int row,int col){
        if(board[i][j] == '#')  //已经访问过
            return;
        char tmp = board[i][j];
        if(root->children[tmp - 'a'] == NULL)
            return ;
        if(root->children[tmp - 'a']->leaf){
            res.push_back(words[root->children[tmp - 'a']->idx]);
            root->children[tmp - 'a']->leaf = false;
        }
        board[i][j] = '#';
        if(i > 0)
            dfs(board,words,res,root->children[tmp - 'a'],i-1,j,row,col);
        if(i < row - 1)
            dfs(board,words,res,root->children[tmp - 'a'],i+1,j,row,col);
        if(j > 0)
            dfs(board,words,res,root->children[tmp - 'a'],i,j-1,row,col);
        if(j < col - 1)
            dfs(board,words,res,root->children[tmp - 'a'],i,j+1,row,col);
        board[i][j] = tmp;
        
    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值