You're given a grid of single-letter cells and a dictionary of words. Return every dictionary word that can be spelled by walking from cell to adjacent cell, never stepping on the same cell twice within one word. This is the core of Boggle — the word game where you race to find words on a tray of lettered dice — and the same shape powers word-search solvers and "find words on a board" autocomplete features.
// grid: string[][]
// A rectangular grid. Each cell is a single, lowercase character.
// grid[r][c] is the letter at row r, column c. All rows have equal length.
// words: string[]
// The dictionary to search for. May contain duplicates.
// returns: string[]
// The subset of `words` that can be traced on the grid, with duplicates
// removed, sorted ascending (lexicographically).
function gridFindWords(grid, words): string[];
A word can be formed if there is a path c0, c1, c2, … of grid cells where grid[c0] is the word's first letter, grid[c1] its second, and so on, each consecutive pair of cells is adjacent, and no cell repeats within that single path.
// "cat" runs left-to-right on row 0; "dog" runs left-to-right on row 1.
// "fox" has no matching path, so it is dropped. Output is sorted.
const grid = [
['c', 'a', 't'],
['d', 'o', 'g'],
];
gridFindWords(grid, ['dog', 'cat', 'fox']); // → ['cat', 'dog']
// 'a' sits at (0,0) and 'b' at (1,1) — they touch only on the diagonal.
// 8-directional adjacency includes diagonals, so "ab" is found.
const grid = [
['a', 'x'],
['x', 'b'],
];
gridFindWords(grid, ['ab']); // → ['ab']
// Only one 'o' cell. Spelling "oo" would need to step on it twice — not
// allowed — so "oo" is not found. "ot" is found (o then t, adjacent).
const grid = [
['o', 't'],
['x', 'y'],
];
gridFindWords(grid, ['oo', 'ot']); // → ['ot']
"cat" twice, the result contains "cat" once. The same word found via two different paths is also returned once. Sort the result ascending.Unlock the solution & editor
Runnable editor + tests
Solve in the browser with instant Jest feedback.
Detailed solutions
Walkthroughs, edge cases, and complexity notes.
Multi-framework variants
React, Vue, Vanilla, Angular — same question, different stacks.