FireEmissary

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  14 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks

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

Note:
You may assume that all inputs are consist of lowercase letters a-z.


做完Word Search点下面的链接跳到212...大量要查找的单词,提示用trie树.网上果然都是用trie树的....不过只需要用到信息能剪枝就好啦就没建立一个真正的trie树.
 struct Layer{
         
int close=0;//>0代表一个完整的词且代表在words里的索引+1
        array<Layer*,26>  next{};//26个字母,不为0即代表当前找到的是前缀或完整词
        ~Layer(){
            
for(Layer*l:next)
              delete l;
        }
    };
    
void find(vector<vector<char>>& board,int i,int j ,vector<string>& words,Layer*lay,vector<string>&res)
    {        
          
char cur=board[i][j];
          
if(cur=='-')return;
          lay
=lay->next[cur-'a'];
          
if(!lay)return;
           
if(lay->close){
              res.push_back(words[lay
->close-1]);
              lay
->close=0;
          }
          board[i][j]
='-';//依然写入其它字符防止重复使用
             if(i+1<board.size())find(board,i+1,j,words,lay,res);
             
if(i>0)find(board,i-1,j,words,lay,res);
             
if(j+1<board[0].size())find(board,i,j+1,words,lay,res);
             
if(j>0)find(board,i,j-1,words,lay,res);
          board[i][j]
=cur;
    }
    vector
<string> findWords(vector<vector<char>>& board, vector<string>& words) {
          Layer root;
          
for(int i=0;i<words.size();++i)
           {
               Layer
*cur=&root;
               
for(char c:words[i]){
                   
if(!cur->next[c-'a']){
                    cur
->next[c-'a']=new Layer;
                   }
                   cur
=cur->next[c-'a'];
               }
               cur
->close=i+1;
           }
          vector
<string> res;
          
for(int i=0;i<board.size();++i)
            
for(int j=0;j<board[0].size();++j)
            {
                find(board,i,j,words,
&root,res);
            }
            
return res;
    }
posted on 2016-03-27 20:57 FireEmissary 阅读(1078) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
【推荐】超50万行VC++源码: 大型组态工控、电力仿真CAD与GIS源码库
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理