Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find multiple words in a grid

Search a grid for multiple given words using backtracking; return which words exist.

Python practice32 minRecursion & BacktrackingAdvancedLast updated March 27, 2026

Problem statement

Given an m x n board of characters and a list of words, return all words that can be found in the board. A word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same cell may not be used more than once in a single word. Return the found words as a list sorted lexicographically and do not include duplicates even if a word can be formed multiple ways.

Task

Implement a search that finds which words from a list are present in a board by connecting adjacent cells (up/down/left/right) without reusing a cell in a single word search.

Examples

Classic example

Input

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

Output

['eat', 'oath']

'oath' and 'eat' can be constructed; 'pea' and 'rain' cannot. Output is sorted.

Input format

Two arguments: board — list of lists of single-character strings; words — list of strings.

Output format

List of found words sorted lexicographically (unique).

Constraints

1 <= m, n <= 6; words length small for brute-force backtracking. You may assume letters are lowercase.

Samples

Sample 1

Input

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

Output

[]

Although 'abc' is adjacent, 'abcb' would require revisiting a cell which isn't allowed.