Word Search II

HardTries

You get a grid of letters, board, and a list of distinct words, words. Return every word that can be spelled on the board, in any order, each word once.

A word is spelled by starting on any cell and stepping to a cell above, below, left or right of the last one (not diagonally), reading one letter per cell. One word cannot use the same cell twice.

On this page the board is an array of rows, and each row is an array of one-letter strings.

Examples

Example 1
Input:  board = [["c", "a", "t"], ["x", "r", "e"], ["b", "o", "w"]], words = ["cat", "care", "bow", "row", "tea"]
Output: ["cat", "care", "bow", "row"]

care turns down from a to r, then right to e. tea fails: no a touches the e.

Example 2
Input:  board = [["a", "b"], ["c", "d"]], words = ["abdc", "acdb", "ad", "aba"]
Output: ["abdc", "acdb"]

a and d touch only at a corner, which does not count, and aba would need the a cell twice.

Constraints

  • 1 ≤ board.length, board[i].length ≤ 12
  • 1 ≤ words.length ≤ 3 × 10⁴
  • 1 ≤ words[i].length ≤ 10
  • The board and the words use lowercase English letters only, and no word repeats in words.

Stuck?

Hint 1

Searching the board once per word repeats the same walks. Put all the words in a trie, and one walk from a cell follows every word that starts there at once.

Hint 2

Run a depth-first search from each cell, moving down the trie as you move across the board, and stop when the trie has no child for the next letter. Mark a cell while it is on the current path, and when you reach a node that ends a word, record the word and clear that mark in the trie so it is not recorded twice.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur