LeetCode 题解(92): Word Search II

题目:

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 I 依次查找words里的每个单词会超时。思路由每次用Word Search I查找word 是否在board里转为, 直接看board上的每个字符,如果该字符存在于由words构建的Trie中,则进行DFS,直到递归到找到某个单词,将该单词加入到result中,同时从Trie中删除该单词。注意Trie需要四个方法:insert, search, searchPre, remove。

C++版:

struct TrieNode {
    bool leaf;
    TrieNode* children[26];
    TrieNode() {
        leaf = false;
        for(int i = 0; i < 26; i++) {
            children[i] = NULL;
        }
    }
};

class Trie {
public:
    TrieNode* root;
    Trie() {
        root = new TrieNode();
    }
    
    ~Trie() {
        delete root;
    }
    
    void insert(string s) {
        TrieNode* p = root;
        for(int i = 0; i < s.length(); i++) {
            if(p->children[s[i]-'a'] == NULL) {
                TrieNode* newNode = new TrieNode();
                p->children[s[i]-'a'] = newNode;
            }
            if(i == s.length() - 1)
                p->children[s[i]-'a']->leaf = true;
            p = p->children[s[i]-'a'];
        }
    }
    
    bool search(string s) {
        if(s.length() == 0)
            return false;
        
        int i = 0;
        TrieNode* p = root;
        while(i < s.length()) {
            if(p->children[s[i]-'a'] == NULL)
                return false;
            else {
                p = p->children[s[i]-'a'];
                i++;
            }
        }
        if(p->leaf == false)
            return false;
        return true;
    }
    
    bool searchPre(string s) {
        if(s.length() == 0)
            return false;
        
        int i = 0;
        TrieNode* p = root;
        while(i < s.length()) {
            if(p->children[s[i]-'a'] == NULL)
                return false;
            else {
                p = p->children[s[i]-'a'];
                i++;
            }
        }
        return true;
    }
    
    void remove(string s) {
        if(s.length() == 0)
            return;
        if(search(s) == false)
            return;
        int i = 0;
        TrieNode* p = root;
        while(i < s.length()) {
            p = p->children[s[i]-'a'];
            i++;
        }
        p->leaf = false;
    }
};

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> results;
        if(words.size() == 0)
            return results;
        Trie tree;
        for(int i = 0; i < words.size(); i++) {
            tree.insert(words[i]);
        }
        
        vector<vector<bool>> used(board.size(), vector<bool>(board[0].size(), false));
        
        for(int i = 0; i < board.size(); i++) {
            for(int j = 0; j < board[0].size(); j++) {
                string s;
                s.push_back(board[i][j]);
                if(tree.search(s)) {
                    results.push_back(s);
                    tree.remove(s);
                }
                else if(tree.searchPre(s)){
                    used[i][j] = true;
                    exist(board, tree, i+1, j, used, s, results);
                    exist(board, tree, i-1, j, used, s, results);
                    exist(board, tree, i, j+1, used, s, results);
                    exist(board, tree, i, j-1, used, s, results);
                    used[i][j] = false;
                }
                s.pop_back();
            }
        }
        return results;
    }
    
    void exist(vector<vector<char>>& board, Trie &tree, int i, int j, vector<vector<bool>> & used, string &s, vector<string>& results) {
        if(i >= board.size() || i < 0 || j >= board[0].size() || j < 0)
            return;
        if(used[i][j] == true)
            return;
        s.push_back(board[i][j]);
        if(tree.search(s)) {
            results.push_back(s);
            tree.remove(s);
        }
        if(tree.searchPre(s)) {
            used[i][j] = true;
            exist(board, tree, i+1, j, used, s, results);
            exist(board, tree, i-1, j, used, s, results);
            exist(board, tree, i, j+1, used, s, results);
            exist(board, tree, i, j-1, used, s, results);
            used[i][j] = false;
        }
        s.pop_back();
    }
};


Java 版:

class TrieNode {
    boolean leaf;
    TrieNode[] children;
    TrieNode() {
        leaf = false;
        children = new TrieNode[26];
    }
}

class Trie {
    TrieNode root = new TrieNode();
    void insert(String s) {
        if(s.length() == 0)
            return;
        TrieNode p = root;
        int i = 0;
        while(i < s.length()) {
            if(p.children[s.charAt(i)-'a'] == null) {
                TrieNode newNode = new TrieNode();
                p.children[s.charAt(i)-'a'] = newNode;
            }
            p = p.children[s.charAt(i)-'a'];
            i += 1;
        }
        p.leaf = true;
    }

    void remove(String s) {
        if(s.length() == 0)
            return;
        if(search(s) == false)
            return;

        TrieNode p = root;
        int i = 0;
        while(i < s.length()) {
            p = p.children[s.charAt(i)-'a'];
            i += 1;
        }
        p.leaf = false;
    }

    boolean search(String s) {
        if(s.length() == 0)
            return false;
        TrieNode p = root;
        int i = 0;
        while(i < s.length()) {
            if(p.children[s.charAt(i)-'a'] == null)
                return false;
            else {
                p = p.children[s.charAt(i)-'a'];
                i += 1;
            }
        }
        if(p.leaf == false)
            return false;
        return true;
    }

    boolean searchPre(String s) {
        if(s.length() == 0)
            return false;
        TrieNode p = root;
        int i = 0;
        while(i < s.length()) {
            if(p.children[s.charAt(i)-'a'] == null)
                return false;
            else {
                p = p.children[s.charAt(i)-'a'];
                i += 1;
            }
        }
        return true;
    }
}

public class Solution {
    public List<String> findWords(char[][] board, String[] words) {
        List<String> result = new ArrayList<>();
        if(board.length == 0 || words.length == 0)
            return result;

        boolean[][] used = new boolean[board.length][board[0].length];

        Trie tree = new Trie();
        for(String word : words) {
            tree.insert(word);
        }

        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                String s = Character.toString(board[i][j]);
                if(tree.search(s) == true) {
                    result.add(s);
                    tree.remove(s);
                }
                if(tree.searchPre(s) == true) {
                    used[i][j] = true;
                    exist(board, words, used, tree, result, s, i+1, j);
                    exist(board, words, used, tree, result, s, i-1, j);
                    exist(board, words, used, tree, result, s, i, j+1);
                    exist(board, words, used, tree, result, s, i, j-1);
                    used[i][j] = false;
                }
            }
        }
        return result;
    }

    void exist(char[][] board, String[] words, boolean[][] used, Trie tree, List<String> result, String s, int i, int j) {
        if(i < 0 || i >= board.length || j < 0 || j >= board[0].length)
            return;
        if(used[i][j] == true)
            return;
        s += Character.toString(board[i][j]);
        if(tree.search(s) == true) {
            result.add(s);
            tree.remove(s);
        }
        if(tree.searchPre(s) == true) {
            used[i][j] = true;
            exist(board, words, used, tree, result, s, i+1, j);
            exist(board, words, used, tree, result, s, i-1, j);
            exist(board, words, used, tree, result, s, i, j+1);
            exist(board, words, used, tree, result, s, i, j-1);
            used[i][j] = false;
        }
        s = s.substring(0, s.length()-1);
    }
}

Python版:

Python版超时,但在local machine上test超时case结果是正确的。同时在Trie上加上记录单词个数的size变量,进一步优化,在local machine上 只需2~3ms。但还是超时。

class TrieNode:
    def __init__(self):
        self.leaf = False
        self.children = [None] * 26

class Trie:
    def __init__(self):
        self.root = TrieNode()
        self.size = 0

    def insert(self, s):
        if len(s) == 0:
            return
        p = self.root
        i = 0
        while i < len(s):
            if p.children[ord(s[i])-ord('a')] is None:
                new_node = TrieNode()
                p.children[ord(s[i])-ord('a')] = new_node
            p = p.children[ord(s[i])-ord('a')]
            i += 1
        p.leaf = True
        self.size += 1

    def remove(self, s):
        if len(s) == 0:
            return
        if not self.search(s):
            return

        p = self.root
        i = 0
        while i < len(s):
            p = p.children[ord(s[i])-ord('a')]
            i += 1
        p.leaf = False
        self.size -= 1

    def search(self, s):
        if len(s) == 0:
            return False
        p = self.root
        i = 0
        while i < len(s):
            if p.children[ord(s[i])-ord('a')] is None:
                return False
            else:
                p = p.children[ord(s[i])-ord('a')]
                i += 1
        if not p.leaf:
            return False
        return True

    def searchPre(self, s):
        if len(s) == 0:
            return False
        p = self.root
        i = 0
        while i < len(s):
            if p.children[ord(s[i])-ord('a')] is None:
                return False
            else:
                p = p.children[ord(s[i])-ord('a')]
                i += 1
        return True

class Solution:
    # @param {character[][]} board
    # @param {string[]} words
    # @return {string[]}
    def findWords(self, board, words):
        result = []
        if len(board) == 0 or len(words) == 0:
            return result

        used = [[False] * len(board[0]) for i in range(len(board)) ]

        tree = Trie()
        for word in words:
            tree.insert(word)

        for i in range(len(board)):
            for j in range(len(board[0])):
                if tree.size == 0:
                    return result
                s = board[i][j]
                if tree.search(s):
                    result.append(s)
                    tree.remove(s)
                if tree.searchPre(s):
                    used[i][j] = True
                    self.exist(board, words, used, tree, result, s, i+1, j)
                    self.exist(board, words, used, tree, result, s, i-1, j)
                    self.exist(board, words, used, tree, result, s, i, j+1)
                    self.exist(board, words, used, tree, result, s, i, j-1)
                    used[i][j] = False

        return result

    def exist(self, board, words, used, tree, result, s, i, j):
        if tree.size == 0:
            return
        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
            return
        if used[i][j]:
            return
        s += board[i][j]
        if tree.search(s):
            result.append(s)
            tree.remove(s)
        if tree.searchPre(s):
            used[i][j] = True
            self.exist(board, words, used, tree, result, s, i+1, j)
            self.exist(board, words, used, tree, result, s, i-1, j)
            self.exist(board, words, used, tree, result, s, i, j+1)
            self.exist(board, words, used, tree, result, s, i, j-1)
            used[i][j] = False
        s = s[0:len(s)-1]




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值