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.
Example:
Solution
Backtracking + Trie. Intuitively, start from every cell and try to build a word in the dictionary.Backtracking (dfs)
is the powerful way to exhaust every possible ways. Apparently, we need to dopruning
when current character is not in any word.
How do we instantly know the current character is invalid?
HashMap
?How do we instantly know what's the next valid character?
LinkedList
?But the next character can be chosen from a list of characters.
"Multi-LinkedList"
?
Combing them,Trie
is the natural choice. Notice that:
TrieNode
is all we need.search
andstartsWith
are useless.No need to store character at TrieNode.
c.next[i] != null
is enough.Never use
c1 + c2 + c3
. UseStringBuilder
.No need to use
O(n^2)
extra spacevisited[m][n].
No need to use
StringBuilder
. Storingword
itself at leaf node is enough.No need to use
HashSet
to de-duplicate. Use "one time search" trie.
For more explanations, check outdietpepsi's blog.
Code Optimization
59ms
: Usesearch
andstartsWith
in Trie class like this popular solution.33ms
: Remove Trie class which unnecessarily starts fromroot
in everydfs
call.30ms
: Usew.toCharArray()
instead ofw.charAt(i)
.22ms
: UseStringBuilder
instead ofc1 + c2 + c3
.20ms
: RemoveStringBuilder
completely by storingword
instead ofboolean
in TrieNode.20ms
: Removevisited[m][n]
completely by modifyingboard[i][j] = '#'
directly.18ms
: check validity, e.g.,if(i > 0) dfs(...)
, before going to the nextdfs
.17ms
: De-duplicatec - a
with one variablei
.15ms
: RemoveHashSet
completely. dietpepsi's idea is awesome.
The algorithm.
Last updated