[leetcode] 212. Word Search II

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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.

Example:

Input:

board = [
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
words = ["oath","pea","eat","rain"]

Output:

["eat","oath"]

Note:

  1. All inputs are consist of lowercase letters a-z.
  2. The values of words are distinct.

分析

题目的意思是:给定一个二维字符矩阵,和一个单词列表,问有多少个单词能够由二维字符矩阵的一条路径构成,其中相同字符单元只能用一次。

  • 首先建立了一个trie的树,然后在这个字典树里面查找。

代码

class TrieNode{
public:
    int isWord;
    vector<TrieNode*> next;
    TrieNode(){
        isWord=-1;
        next=vector<TrieNode*>(26,NULL);
    }
};

class Solution {
private:
    TrieNode* root;
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        root=new TrieNode();
        buildTree(words,root);
        set<string> res;
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[i].size();j++){
                findWords(res,board,words,root,i,j);
            }
        }
        return vector<string>(res.begin(),res.end());
        
    }
    
    void findWords(set<string>& res, vector<vector<char>>& board, vector<string>& words, TrieNode* node, int r, int c){
        if(board[r][c] == '.' || !node->next[board[r][c]-'a']) return;
        TrieNode* after=node->next[board[r][c]-'a'];
        if(after->isWord>-1){
            res.insert(words[after->isWord]);
        }
        char letter=board[r][c];
        board[r][c]='.';
        if(r-1>=0){
            findWords(res,board,words,after,r-1,c);
        }
        if(r+1<board.size()){
            findWords(res,board,words,after,r+1,c);
        }
        if(c-1>=0){
            findWords(res,board,words,after,r,c-1);
        }
        if(c+1<board[0].size()){
            findWords(res,board,words,after,r,c+1);
        }
        board[r][c]=letter;
        
    }
    
    void buildTree(vector<string>& words,TrieNode* root){
        TrieNode* cur;
        for(int i=0;i<words.size();i++){
            cur=root;
            for(char c:words[i]){
                if(!cur->next[c-'a']){
                    cur->next[c-'a']=new TrieNode();
                }
                cur=cur->next[c-'a'];
            }
            cur->isWord=i;
        }
    }
};

参考文献

212. Word Search II

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值