Skip to the code
cf.
+50 XP

#371 Spell Words on a Letter Grid

hard

A word game in your app shows a grid of letters. A word can be spelled by starting on any cell and moving to a neighboring cell (up, down, left, or right) for each next letter. A cell can't be used twice in the same word.

Write findWords(board, words) that returns every word from words that can be spelled on board, each once, sorted alphabetically. board is an array of equal-length strings, one per row.

Example 1

Input: board = ["cat","ore","dog"], words = ["cat","cord","dog","toe","rat"]
Output: ["cat","dog","rat"]

rat goes from the middle r up to a, then right to t. cord fails because d is not next to r.

Example 2

Input: board = ["ab","cd"], words = ["abdc","abcd"]
Output: ["abdc"]

a → b → d → c follows neighbors; in abcd, b and c are not neighbors.

Constraints

  • 1 <= rows, columns <= 12
  • 1 <= words.length <= 3 * 10^4
  • 1 <= words[i].length <= 10
  • Only lowercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).