`

LeetCode 212 - 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.

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.

public static final int[][] DIR = {{1,0}, {-1,0}, {0,1}, {0,-1}};
public static class TrieNode{
    TrieNode[] children = new TrieNode[26];
    boolean isLeaf;
}
public void insert(TrieNode node, String word, int pos) {
    if(pos >= word.length()) {
        node.isLeaf = true;
        return;
    }
    int index = word.charAt(pos)-'a';
    if(node.children[index] == null) {
        node.children[index] = new TrieNode();
    }
    insert(node.children[index], word, pos+1);
}
public void check(char[][] board, TrieNode node, int row, int col, StringBuilder sb, Set<String> list) {
    int m = board.length, n = board[0].length;
    if(row>=m || row<0 || col>=n || col<0 || board[row][col] == '.') return;
    char c = board[row][col];
    board[row][col] = '.';
    TrieNode child = node.children[c - 'a'];
    if(child != null) {
        sb.append(c);
        if(child.isLeaf) 
            list.add(sb.toString());
        for(int i=0; i<DIR.length; i++)
            check(board, child, row+DIR[i][0], col+DIR[i][1], sb, list);
        sb.deleteCharAt(sb.length()-1);
    }
    board[row][col] = c;
}
public List<String> findWords(char[][] board, String[] words) {
    Set<String> set = new HashSet<>();
    int m = board.length, n = board[0].length;
    TrieNode root = new TrieNode();
    for(String word:words) { // build trie from words
        insert(root, word, 0);
    }
    StringBuilder sb = new StringBuilder();
    for(int i=0; i<m; i++) {
        for(int j=0; j<n && set.size()<words.length; j++) {
            check(board, root, i, j, sb, set);
        }
    }
    return new ArrayList<>(set);
}

  

分享到:
评论

相关推荐

    js-leetcode题解之79-word-search.js

    javascript js_leetcode题解之79-word-search.js

    leetcode耗时-word-search-ii:查词二

    leetcode 耗时查词二 给定一个 2D 板和字典中的单词列表,找到板中的所有单词。 每个单词必须由顺序相邻单元格的字母构成,其中“相邻”单元格是水平或垂直相邻的单元格。 同一个字母单元格不能在一个单词中多次使用...

    python-leetcode题解之079-Word-Search

    python python_leetcode题解之079_Word_Search

    c语言-leetcode题解之0079-word-search.zip

    c c语言_leetcode题解之0079_word_search.zip

    leetcode1-200题源码(c++)

    4. 题目79:单词搜索 (Word Search) 在一个二维字符网格中查找给定的单词,使用深度优先搜索(DFS)或广度优先搜索(BFS)策略,结合回溯技术来实现。 5. 题目4:寻找两个有序数组的中位数 (Median of Two Sorted ...

    leetcode不会-word-search:二维网格中的单词搜索

    leetcode 不会词搜索 给定一个 2D 板和一个单词,查找该单词是否存在于网格中。 单词可以由顺序相邻的单元格的字母构成,其中“相邻”单元格是水平或垂直相邻的单元格。 同一个字母单元格不能多次使用。 Example: ...

    _leetcode-python.pdf

    - Word Search: 给定一个m×n的二维字符网格board和一个单词(字符串)word,如果word存在于网格中,则返回true;否则,返回false。 - Minimum Window Substring: 给定两个字符串s和t,找出s中包含t所有字母的最小子...

    扩展矩阵leetcode-Leetcode:LeetcodeAnswer-Java

    扩展矩阵leetcode ...63.不同路径II uniquePathsWithObstacles 139.单词拆分 wordBreak 279.完全平方数 numSquares 排序 56.合并区间 merge 75.颜色分类 sortColors 179.最大数 largestNumber 324.摆

    leetcode苹果-LeetCode_No.208_-:LeetCode_No.208_-

    leetcode 苹果 LeetCode_No.208_-实现 Trie (前缀树) 题目介绍 Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完...

    LeetCode最全代码

    * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...

    leetcode答案-exercise-book:算法练习记录

    II 解决方法:Majority Voting算法的变种。但是最终的算法实现形式,很难理解。 2018-08-19 19:16 LeetCode: 79. Word Search 解决方法:DFS LeetCode: 31. Next Permutation 解决方法:掌握排列组合的字典序规律,...

    leetcode338-LeetCode:力码

    单词搜索II(Word Search II)**:这是单词搜索问题的升级版,需要在一个二维字符网格中寻找多个给定单词。此题需要用到回溯法和动态规划,同时理解字符串匹配算法如KMP或Rabin-Karp。 4. **301. 删除无效的括号...

    leetcode浇花-LCSolutions:我的力扣解决方案

    leetcode 浇花力扣解决方案 简单的 #0001 - Two Sum #0007 - Reverse Integer #0009 - Palindrome Number #0035 - Search Insert Position #0058 - Length of Last Word #0066 - Plus One #0083 - Remove Duplicates...

    leetcode答案-leetcode:leetcode

    Search)+ 鸽笼原理(Pigeonhole Principle) “不允许修改数组” 与 “常数空间复杂度”这两个限制条件意味着:禁止排序,并且不能使用Map等数据结构 小于O(n2)的运行时间复杂度可以联想到使用二分将其中的一个n...

    leetcode分类-leetcode:leetcode刷题

    1. **字符串匹配**:如“单词搜索”(Word Search),需要在一个二维字符网格中查找给定单词。 2. **字符串反转与替换**:如“反转字符串”(Reverse String)和“替换空格”(Replace Spaces)。 3. **字符串哈希...

    leetcode不会-interview_practice:将我所有的编码面试实践整合到一个地方

    leetcode/0079-word-search - 我的解决方案太冗长了(逻辑很好) hackerrank/data_structures/trie/contacts.py 我做了一个 trie 的完整实现,但实际上这个问题不需要前缀补全,只需要知道子树中的节点数,这在插入...

    LeetCode:关于LeetCode.com和ACM的一些算法问题

    LeetCode一些 LeetCode 题目的进阶解法,追求极致效率。由于 LeetCode 已启用中文版域名 leetcode-... Word-Search-II题目: | 英文站源码:./problem-0212-Word-Search-II/标签:哈希表,双向链表难度:困难 / Hard

    leetcode添加元素使和等于-Leetcode-Problems-Java-Python--with-Markdown-Explanati

    leetcode添加元素使和等于 October 2nd Reviews 79 word Search Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, ...

    AlgorithmAndLeetCode#itcharge-LeetCode-Py#0211. 添加与搜索单词 - 数据结构设计

    void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配bool search(word) 如果数据结构中存在字符串与 wor

Global site tag (gtag.js) - Google Analytics