• Word Search II 解答


    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.

    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.

    Solution

    If the current candidate does not exist in all words' prefix, we can stop backtracking immediately. This can be done by using a trie structure.

     1 public class Solution {
     2     Set<String> result = new HashSet<String>();
     3     
     4     public List<String> findWords(char[][] board, String[] words) {
     5         Trie trie = new Trie();
     6         for (String word : words)
     7             trie.insert(word);
     8         int m = board.length, n = board[0].length;
     9         boolean[][] visited = new boolean[m][n];
    10         for (int i = 0; i < m; i++) {
    11             for (int j = 0; j < n; j++) {
    12                 dfs(board, "", i, j, trie, visited);
    13             }
    14         }
    15         return new ArrayList<String>(result);
    16     }
    17     
    18     private void dfs(char[][] board, String prev, int startX, int startY, Trie trie, boolean[][] visited) {
    19         int m = board.length, n = board[0].length;
    20         if (startX < 0 || startX >= m || startY < 0 || startY >= n)
    21             return;
    22         if (visited[startX][startY])
    23             return;
    24         String current = prev + board[startX][startY];
    25         if (!trie.startsWith(current))
    26             return;
    27         if (trie.search(current))
    28             result.add(current);
    29         visited[startX][startY] = true;
    30         dfs(board, current, startX + 1, startY, trie, visited);
    31         dfs(board, current, startX - 1, startY, trie, visited);
    32         dfs(board, current, startX, startY + 1, trie, visited);
    33         dfs(board, current, startX, startY - 1, trie, visited);
    34         visited[startX][startY] = false;
    35     }
    36 }

    Construct Trie

     1 class TrieNode {
     2     public char value;
     3     public boolean isLeaf;
     4     public HashMap<Character, TrieNode> children;
     5     
     6     // Initialize your data structure here.
     7     public TrieNode(char c) {
     8         value = c;
     9         children = new HashMap<Character, TrieNode>();
    10     }
    11 }
    12 
    13 class Trie {
    14     TrieNode root;
    15 
    16     public Trie() {
    17         root = new TrieNode('!');
    18     }
    19 
    20     // Inserts a word into the trie.
    21     public void insert(String word) {
    22         char[] wordArray = word.toCharArray();
    23         TrieNode currentNode = root;
    24         
    25         for (int i = 0; i < wordArray.length; i++) {
    26             char c = wordArray[i];
    27             HashMap<Character, TrieNode> children = currentNode.children;
    28             TrieNode node;
    29             if (children.containsKey(c)) {
    30                 node = children.get(c);
    31             } else {
    32                 node = new TrieNode(c);
    33                 children.put(c, node);
    34             }
    35             currentNode = node;
    36             
    37             if (i == wordArray.length - 1)
    38                 currentNode.isLeaf = true;
    39         }
    40         
    41     }
    42 
    43     // Returns if the word is in the trie.
    44     public boolean search(String word) {
    45         TrieNode currentNode = root;
    46         for (int i = 0; i < word.length(); i++) {
    47             char c = word.charAt(i);
    48             HashMap<Character, TrieNode> children = currentNode.children;
    49             if (children.containsKey(c)) {
    50                 TrieNode node = children.get(c);
    51                 currentNode = node;
    52                 // Need to check whether it's leaf node
    53                 if (i == word.length() - 1 && !node.isLeaf)
    54                     return false;
    55             } else {
    56                 return false;
    57             }
    58         }
    59         return true;
    60     }
    61 
    62     // Returns if there is any word in the trie
    63     // that starts with the given prefix.
    64     public boolean startsWith(String prefix) {
    65         TrieNode currentNode = root;
    66         for (int i = 0; i < prefix.length(); i++) {
    67             char c = prefix.charAt(i);
    68             HashMap<Character, TrieNode> children = currentNode.children;
    69             if (children.containsKey(c)) {
    70                 TrieNode node = children.get(c);
    71                 currentNode = node;
    72             } else {
    73                 return false;
    74             }
    75         }
    76         return true;
    77     }
    78 }
  • 相关阅读:
    视觉SLAM十四讲课后习题—ch13
    视觉SLAM中涉及的各种坐标系转换总结
    《视觉SLAM十四讲》笔记(ch13)
    《视觉SLAM十四讲》笔记(ch12)
    《视觉SLAM十四讲》课后习题—ch7(更新中……)
    安装opencv_contrib(ubuntu16.0)
    《视觉SLAM十四讲》笔记(ch8)
    如何将“您没有打开此文件的权限”的文件更改为可读写的文件
    《视觉SLAM十四讲》笔记(ch7)
    ubuntu16.04下跑通LSD-SLAM的过程记录
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4876414.html
Copyright © 2020-2023  润新知