HardTrieBacktrackingDepth-First SearchMatrix

1 approach, code in every language

Problem description

You are given an m x n grid of lowercase letters and a list of target words. A word is present in the grid if its letters can be spelled out by moving through a sequence of adjacent cells, where adjacent means horizontally or vertically neighboring. The same cell cannot be reused within a single word.

Return every word from the list that can be formed this way. The order of the returned words does not matter, and each found word should appear only once.

Example 1

Input: board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ], words = ['oath','pea','eat','rain']

Output: ['oath','eat']

'oath' traces through connected cells starting at the top-left, and 'eat' can be spelled out; 'pea' and 'rain' have no valid connected path.

Example 2

Input: board = [['a','b'],['c','d']], words = ['abcb']

Output: []

Forming 'abcb' would require revisiting the cell holding 'b', which is not allowed, so no word is returned.

Constraints

  • m == board.length and n == board[i].length
  • 1 ≤ m, n ≤ 12
  • 1 ≤ words.length ≤ 3 * 10^4
  • 1 ≤ words[i].length ≤ 10

After the pattern

Now solve one you haven't seen.

Letter Plate Catalogue is our own problem on the technique behind Word Search II: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free