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 =

  1. [
  2. ['o','a','a','n'],
  3. ['e','t','a','e'],
  4. ['i','h','k','r'],
  5. ['i','f','l','v']
  6. ]

Return ["eat","oath"].

Note:

You may assume that all inputs are consist of lowercase letters a-z.

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.

Solution:

  1. public class Solution {
  2. int[] dx = {-1, 1, 0, 0};
  3. int[] dy = {0, 0, -1, 1};
  4. public List<String> findWords(char[][] board, String[] words) {
  5. List<String> res = new ArrayList<String>();
  6. int n = board.length;
  7. int m = board[0].length;
  8. boolean[][] used = new boolean[n][m];
  9. // use a hashset to avoid duplicates
  10. Set<String> set = new HashSet<String>();
  11. // use a trie tree to avoid unnecessary search
  12. Trie trie = new Trie();
  13. for (String word : words)
  14. trie.insert(word);
  15. // perform dfs from each position
  16. for (int i = 0; i < n; i++)
  17. for (int j = 0; j < m; j++)
  18. search(board, n, m, i, j, "", used, trie, set, res);
  19. return res;
  20. }
  21. void search(char[][] board, int n, int m, int i, int j, String word, boolean[][] used, Trie trie, Set<String> set, List<String> res) {
  22. if (i < 0 || i >= n || j < 0 || j >= m || used[i][j])
  23. return;
  24. word += board[i][j];
  25. // not the word we are looking for
  26. if (!trie.startsWith(word))
  27. return;
  28. if (!set.contains(word) && trie.search(word)) {
  29. // found the word
  30. set.add(word);
  31. res.add(word);
  32. }
  33. used[i][j] = true;
  34. for (int d = 0; d < 4; d++)
  35. // continue dfs
  36. search(board, n, m, i + dx[d], j + dy[d], word, used, trie, set, res);
  37. // backtracking
  38. used[i][j] = false;
  39. }
  40. class TrieNode {
  41. // Initialize your data structure here.
  42. char c;
  43. boolean isLeaf;
  44. Map<Character, TrieNode> children = new HashMap<Character, TrieNode>();
  45. public TrieNode() {}
  46. public TrieNode(char c) { this.c = c; }
  47. }
  48. public class Trie {
  49. private TrieNode root;
  50. public Trie() {
  51. root = new TrieNode();
  52. }
  53. // Inserts a word into the trie.
  54. public void insert(String word) {
  55. Map<Character, TrieNode> children = root.children;
  56. for (int i = 0; i < word.length(); i++) {
  57. char c = word.charAt(i);
  58. if (!children.containsKey(c))
  59. children.put(c, new TrieNode(c));
  60. TrieNode t = children.get(c);
  61. if (i == word.length() - 1)
  62. t.isLeaf = true;
  63. children = t.children;
  64. }
  65. }
  66. // Returns if the word is in the trie.
  67. public boolean search(String word) {
  68. TrieNode t = searchLastNode(word);
  69. return t != null && t.isLeaf;
  70. }
  71. // Returns if there is any word in the trie
  72. // that starts with the given prefix.
  73. public boolean startsWith(String prefix) {
  74. return searchLastNode(prefix) != null;
  75. }
  76. // Returns the last TrieNode of word
  77. private TrieNode searchLastNode(String word) {
  78. Map<Character, TrieNode> children = root.children;
  79. for (int i = 0; i < word.length(); i++) {
  80. char c = word.charAt(i);
  81. if (!children.containsKey(c))
  82. break;
  83. TrieNode t = children.get(c);
  84. if (i == word.length() - 1)
  85. return t;
  86. children = t.children;
  87. }
  88. return null;
  89. }
  90. }
  91. }