Word Search II

Hard Tries AI round

board is a grid of m rows and n columns, each cell holding a lowercase letter. words is a list of different words, also of lowercase letters.

A word is on the board when a walk spells it: start on a cell holding its first letter, then step each time to a cell above, below, left or right of the one you are on, holding the next letter. A walk never comes back to a cell it has used, though different words may use the same cells.

Return every word of words that is on the board, in any order. Each appears once in the answer, however many walks spell it.

Example 1

Input: board = [["c","a","t","s"],["o","r","e","d"],["w","i","n","g"]], words = ["cat","ring","tree","red","tat"]
Output: ["cat","ring","red"]

cat runs along the top row, ring goes down from r and then along the bottom row, and red along the middle row. tree has no r next to its t, and tat would need the one t twice.

Example 2

Input: board = [["t","o"],["e","n"]], words = ["tone","toe","net","toot"]
Output: ["tone","net"]

tone goes round the board. toe would need a diagonal step from o to e, and toot needs a second t and o.

Example 3

Input: board = [["b","e","e"],["e","b","e"]], words = ["bee","bebe","ebb"]
Output: ["bee","bebe"]

Constraints

  • 1 ≤ m, n ≤ 12
  • board[i][j] is a lowercase English letter
  • 1 ≤ words.length ≤ 2 × 10⁴
  • 1 ≤ words[i].length ≤ 10, and words[i] is lowercase English letters
  • The words in words are all different

More Tries

All Tries problems