Friday, November 25, 2016

Word Search II -- LeetCode

[Question]
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.

[Analysis]
This is a typical Back Tracking problem. Using DFS to explore every letter on the board. Trie can be used to trim the branches of DFS -- no need to travel on string path which is not a prefix of any words in the target set. The time complexity is O(MxNxL) L is the number of nodes in Trie.

[Solution]
class TrieNode {
public:
    bool isWord;
    vector<TrieNode *> letters;
    // Initialize your data structure here.
    TrieNode(): isWord(false) {
        letters.resize(26, NULL);
    }
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode* p=root;
        for (auto c: word) {
            int i =c-'a';
            if (!p->letters[i])
                p->letters[i] = new TrieNode();
            p = p->letters[i];
        }
        p->isWord = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode* p=root;
        for (auto c: word) {
            int i = c-'a';
            if (!p->letters[i]) return false;
            p = p->letters[i];
        }
        return p->isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode* p=root;
        for (auto c: prefix) {
            int i = c-'a';
            if (!p->letters[i]) return false;
            p = p->letters[i];
        }
        return true;
    }

    TrieNode* getRoot() {
        return root;
    }
private:
    TrieNode* root;
};

class Solution {
    Trie trie;
    int limit;
    vector<pair<int,int>> dd = {{0,1},{0,-1},{1,0},{-1,0}};  
   
    void searchWords( vector<vector<char>>& b, int i, int j, string s, TrieNode* p, set<string>& res) {
        char cur = b[i][j];
        if (s.size() == limit) return;
        p = p->letters[cur-'a'];
        if (p==NULL) return;
        if (p->isWord) res.insert(s+cur);

        b[i][j] = ' ';
        for (auto& d : dd) {
            int x = i+d.first, y=j+d.second;
            if ( 0<=x && x<b.size() && 0<=y && y<b[0].size() && b[x][y]!=' ' )
                searchWords(b, x, y, s+cur, p, res);
        }
        b[i][j]= cur;
    }
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        limit = 0;
        for (auto& w: words) {
            trie.insert(w);
            limit = max(limit, (int)w.size() );
        }
       
        set<string> res;
        for (int i=0; i<board.size(); i++)
            for (int j=0; j<board[0].size(); j++) {
                searchWords( board, i, j, "", trie.getRoot(), res);
            }
        return vector<string>(res.begin(),  res.end());
    }

};

No comments:

Post a Comment