All topics
142

Find a word on a letter grid

Tier 1Locked

Where it runs

1. The problem

You have a grid of letters and one word. Can you spell the word by walking the grid one cell at a time? You may move only up, down, left or right, never diagonally. You may not step on the same cell twice. Answer yes or no.

The hard part is that one letter can sit in many places, so there are many paths to check. You need a way to try a path and, when it hits a dead end, step back and try another one.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included
Finding "TOP" on a letter grid
exist([["C", "A", "T", "S"], ["A", "X", "T", "O"], ["T", "O", "P", "S"]], "TOP")
board (highlighted cells are on the current path)
0123
0CATS
1AXTO
2TOPS
word
TOP
i = 0path = -

Does "TOP" appear as a path of neighbouring cells, each used once? Try a start from every cell in turn.

Recognise it

Matrix word search (grid DFS/backtracking)

Say these words and it is this pattern

  • does the word exist as a path on the board
  • trace letters through adjacent cells, no reuse
  • DFS with backtracking on a grid
  • mark a cell as visited, then undo it

Looks similar, isn't

  • Backtracking

    This is backtracking with the grid as the tree. The choices are the four neighbours.

  • Graph BFS / DFS

    A traversal marks a cell once and forever. Here the mark comes off on the way out.

  • Connected components

    Flood fill also walks neighbours, but it never unmarks. It is counting rather than searching.

  • Trie (prefix tree)

    With many words to find, a trie prunes the walk. Without one each word costs its own search.

An r by c grid with a word of length L costs O(rc times 4L). Pruning is what makes it run.

On LeetCode

Grid problems that look for a path through neighbouring cells without reusing a cell, such as spelling a word or collecting the most gold. A DFS marks the cell, tries the four neighbours and puts the cell back on the way out.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy