212. Word Search II

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.

For example,
Givenwords=["oath","pea","eat","rain"]andboard=

[
  ['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 lettersa-z.

Discussion

trie + dfs

Warning:

Need to carefully consider when it should insert the word.

Will the word get inserted multiple time?

class Trie {
public:
    unordered_map<char, Trie*> trie;
    string word;
    void insert(string &word) {
        Trie *node = this;
        Trie *pre = this;
        for(auto chr : word) {
            if(node->trie.find(chr) == node->trie.end()) {
                node->trie[chr] = new Trie();
            }
            pre = node;
            node = node->trie[chr];
        }
        node->word = word;
    }
};
class Solution {
    Trie tree;
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> rst;
        if(0 == board.size()) {
            return rst;
        }
        for(auto &word:words){
            tree.insert(word);
        }

        for(int yLoop = 0; yLoop < board.size(); ++yLoop) {
            for(int xLoop = 0; xLoop < board[0].size(); ++xLoop) {
                vector<vector<bool>> visited (board.size(), vector<bool>(board[0].size(), false));
                dfs(board, visited, yLoop, xLoop, rst, &tree);
            }
        }

        return rst;
    }

    void dfs(vector<vector<char>>& board, vector<vector<bool>> &visited, int y, int x, vector<string> &rst, Trie *node) {
        vector<int> dy = {0,0,1,-1};
        vector<int> dx = {1,-1,0,0};

        //cout << "[" << y << ", " << x << "]" << endl;

        visited[y][x] = true;
        if(node->trie.find(board[y][x]) != node->trie.end()) {
            node = node->trie[board[y][x]];
            if(node->word.size() != 0) {
                //cout << "insert:[" << y << ", " << x << "]" << endl;
                //cout << "insert: " << node->word << endl; 
                rst.push_back(node->word);
                node->word.clear();
            }
            for(int loop = 0; loop < dy.size(); ++loop) {
                if(y + dy[loop] >= 0 && y + dy[loop] < board.size() &&
                   x + dx[loop] >= 0 && x + dx[loop] < board[0].size() &&
                   visited[y+dy[loop]][x+dx[loop]] == false) {
                    dfs(board, visited, y+dy[loop],x+dx[loop], rst, node);
                }
            }
        }
        visited[y][x] = false;
    }
};

results matching ""

    No results matching ""