← Whiteboard questions

Word Search

Find a word as a path of neighbouring cells in a grid

DSA, Medium, Backtracking

Which structure or algorithm, and what does it cost.

A grid is a list of strings of equal length. Each string is one row of lowercase letters. Return true if word can be spelled by a path of cells. A path starts at any cell. Each step moves up, down, left or right to a neighbouring cell. One path may not use a cell twice. Otherwise return false.

Examples

Input grid = ["ndo", "aet", "rhs"], word = "shed"
Output true
Why the path goes s, h, e, d by moving left, up, up.
Input grid = ["ndo", "aet", "rhs"], word = "deed"
Output false
Why the grid has only one e, and a path cannot use a cell twice.
Input grid = ["k"], word = "k"
Output true
Why a one-cell grid holds a one-letter word.

Constraints

Your answer must contain

Target Aim to drop a path on the first wrong letter, so most starts die after one or two steps.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Any cell can start the path. From a cell that matches the first letter, where can the next letter be?

Hint 2 the approach

Each step is the same question for a shorter word.

Hint 3 the key step

Write a call for a cell and a letter position. Fail on the edge, a used cell or a wrong letter. Mark the cell, try four neighbours, then unmark it.

Walkthrough

Full walkthrough brute force to best

Brute force

From every cell, build every path of the word's length that never reuses a cell, then compare the letters of each path with the word. There are up to rows * columns starts, and each has about 4 * 3^(L - 1) paths for a word of L letters. Most of that work is wasted on paths that went wrong at the first letters.

Best method

Try every cell as a start. A call takes a cell and a position k in the word. It returns true when k equals the length of the word. It returns false when the cell is outside the grid, is already on the path, or holds a letter that is not the letter at position k. Otherwise it marks the cell, tries the four neighbours with position k + 1, and unmarks the cell. Unmarking lets other paths use the cell again. A wrong letter stops a path at once, so most paths end after one or two steps.

Hand trace

Run on the grid with the word shed. The cells n, d, o, a, e, t, r and h in row order are not s, so each start fails at once. The cell s at row 2, column 2 matches. For h: below is outside, above is t, right is outside, left is h, which matches. For e: below is outside and above is e, which matches. For d: below is h, which is already on the path, so it fails, and above is d, which matches. The position now equals the length of the word, so the answer is true.

Code

def word_exists(grid, word):
    rows, cols = len(grid), len(grid[0])
    used = set()
    def go(r, c, k):
        if k == len(word):
            return True
        if r < 0 or r >= rows or c < 0 or c >= cols:
            return False
        if (r, c) in used or grid[r][c] != word[k]:
            return False
        used.add((r, c))
        found = (go(r + 1, c, k + 1) or go(r - 1, c, k + 1)
                 or go(r, c + 1, k + 1) or go(r, c - 1, k + 1))
        used.remove((r, c))
        return found
    return any(go(r, c, 0) for r in range(rows) for c in range(cols))

Time and memory

O(R * C * 3^L) time in the worst case for R rows, C columns and a word of L letters: each start has at most 4 first steps and then at most 3, because one neighbour is the cell the path came from. Extra memory is O(L) for the recursion if cells are marked in the grid itself, or O(R * C) with a separate visited grid.

Common mistakes

  • Forgetting to unmark the cell when the call returns. A failed path then blocks cells that other paths need.
  • Reading the cell before checking the edges, which reads outside the grid.
  • Starting only at one cell. Any cell with the first letter can start the path.

Related problems

More Backtracking problems
Word Search: hints, walkthrough and Python solution