Skip to content
BytePatterns

Dictionary Words In A Grid

HardTries#trie#backtracking#grid-dfs~45m

Problem

You are given a grid of lowercase letters and a list of distinct words. A word is present if it can be spelled by a path that starts on any cell and moves up, down, left or right one cell at a time, never using the same cell twice within that word. Return every present word, each once, in alphabetical order.

Examples

Input:  grid = [["o", "a", "a", "n"],
                ["e", "t", "a", "e"],
                ["i", "h", "k", "r"],
                ["i", "f", "l", "v"]],
        words = ["oath", "pea", "eat", "rain"]
Output: ["eat", "oath"]
Input:  grid = [["a", "b"],
                ["c", "d"]], words = ["abdc", "abcb"]
Output: ["abdc"]
Why:    "abcb" would need the b cell twice
Input:  grid = [["a"]], words = ["a", "aa"]
Output: ["a"]
Why:    edge case, a one-cell grid can only spell one-letter words

Hints

0 / 3

Stuck on the idea rather than the code? Word Search With a Trie covers it.