首页 > 其他 > 详细

212. Word Search II

时间:2017-03-25 00:44:27      阅读:293      评论:0      收藏:0      [点我收藏+]

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

 解题思路:字典树+dfs。刚开始用的暴力,过了35/37的数据,比较满意。想不到怎么优化剪枝,看了下discuss,还是要用高级数据结构啊。

暴力代码:

int dirs[][4]={{1,0},{0,1},{-1,0},{0,-1}};
class Solution {
public:
    bool isOk(string str,int index,vector<vector<int>> vis,vector<vector<char>>& board,int x,int y){
        int n=board.size(),m=board[0].size();
        if(str[index-1]!=board[x][y])return false;
        if(index == str.length()){
            return true;
        }
        vis[x][y]=1;
        for(auto dir: dirs){
            int xx=x+dir[0],yy=y+dir[1];
            if(xx>=0&&xx<n&&yy>=0&&yy<m&&!vis[xx][yy]){
                if(isOk(str,index+1,vis,board,xx,yy))return true;
            }
        }
        return false;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        set<string>swords(words.begin(),words.end());
        int n=board.size(),m=board[0].size();
        set<string>ans;
        int flag=0;
        for(auto word: swords){
            if(word.length()>n*m)continue;
            flag=0;
             for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    if(board[i][j] == word[0]){
                        vector<vector<int>> vis(n,vector<int>(m,0));
                        if(isOk(word,1,vis,board,i,j)){
                            ans.insert(word);
                            flag=1;
                            break;
                        }
                    }
                    if(flag)break;
                }
            }
        }
    return vector<string>(ans.begin(),ans.end());
    }
};

 

Trie+dfs代码:

class Solution {
public:
    struct TrieNode{
        vector<TrieNode* >child;
        string word;
        TrieNode():word(""),child(vector<TrieNode*>(26,nullptr)){};
    };
    TrieNode* buildTree(vector<string>& words){
        TrieNode* root = new TrieNode();
        for(string word: words){
            TrieNode* temp=root;
            for(char c: word){
                int i = c - ‘a‘;
                if(temp->child[i]==NULL)temp->child[i] = new TrieNode();
                temp=temp->child[i];
            }
            temp->word=word;
        }
        return root;
    }

    void dfs(vector<vector<char>>& board,int x,int y,TrieNode* root,vector<string>&ans){
        char c=board[x][y];
        if(c==‘#‘||root->child[c-‘a‘]==NULL)return;
        root=root->child[c-‘a‘];
        if(root->word!=""){
            ans.push_back(root->word);
            root->word="";
        }
        board[x][y]=‘#‘;
        if(x>0)dfs(board,x-1,y,root,ans);
        if(y>0)dfs(board,x,y-1,root,ans);
        if(x+1<board.size())dfs(board,x+1,y,root,ans);
        if(y+1<board[0].size())dfs(board,x,y+1,root,ans);
        board[x][y]=c;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string>ans;
        TrieNode* root=buildTree(words);
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[0].size();j++)
                dfs(board,i,j,root,ans);
        }
        return ans;
    }
};

 

212. Word Search II

原文:http://www.cnblogs.com/tsunami-lj/p/6614055.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!