LeetCode - Word Search II

来源:互联网 发布:ansys软件和fluent 编辑:程序博客网 时间:2024/05/17 07:04

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.

click to show hint.

You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?

If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.




class TrieNode {public:    char val;    TrieNode *children[26];    bool tail;    // Initialize your data structure here.    TrieNode() {        val = '\0';        for(int i = 0; i < 26; ++i)            children[i] = nullptr;        tail = false;    }    TrieNode(char c): val(c){        for(int i = 0; i < 26; ++i)            children[i] = nullptr;        tail = false;    }};class Trie {public:    Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    void insert(string word) {        TrieNode *p = root;        int l = word.length();        for(int i = 0; i < l; ++i){            int j = word[i] - 'a';            if(!p->children[j]){                p->children[j] = new TrieNode(word[i]);            }            p = p->children[j];        }        p->tail = true;    }    // Returns if the word is in the trie.    bool search(string word) {        TrieNode *p = root;        int l = word.length();        for(int i = 0; i < l; ++i){            int j = word[i] - 'a';            if(!p->children[j])                return false;            p = p->children[j];        }        return p->tail;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {        TrieNode *p = root;        int l = prefix.length();        for(int i = 0; i < l; ++i){            int j = prefix[i] - 'a';            if(!p->children[j])                return false;            p = p->children[j];        }        return true;    }        TrieNode* getRoot(){        return root;    }private:    TrieNode* root;};class Solution {public:    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {        ret.clear();        if(((n = board.size()) == 0) || ((m = board[0].size()) == 0))            return ret;        v = vector<vector<bool>> (n, vector<bool> (m, false));        for(auto &s : words)            trie.insert(s);        TrieNode *root = trie.getRoot();        for(int i = 0; i < n; ++i)        for(int j = 0; j < m; ++j)            if(root->children[board[i][j] - 'a']){                dfs(board, root->children[board[i][j] - 'a'], i, j, string("") + board[i][j]);             }        return ret;    }private:    Trie trie;    vector<string> ret;    vector<vector<bool>> v;    int n, m;    bool flag = false;    int dx[4] = {0, 0, -1, 1};    int dy[4] = {-1, 1, 0, 0};    void dfs(vector<vector<char> > &board, TrieNode *root, int i, int j, string cur){        if(root->tail){            ret.push_back(cur);            root->tail = false;        }        v[i][j] = true;        for(int d = 0; d < 4; ++ d){            int x = i + dx[d];            int y = j + dy[d];            if(x >= 0 && x < n && y >= 0 && y < m && !v[x][y] && root->children[board[x][y] - 'a']){                dfs(board, root->children[board[x][y] - 'a'], x, y, cur + board[x][y]);            }        }        v[i][j] = false;    }};


0 0
原创粉丝点击