Find Word in GridLoading saved progress…

Find Word in Grid

Implement gridFindWord(grid, word) — given a 2D grid of single-character cells and a target word, return true if the word can be spelled by tracing a path through adjacent cells, and false otherwise. This is the core check behind a word-search puzzle: starting from some cell, each next letter must sit in a cell directly above, below, left, or right of the current one (not diagonally), and you may not step on the same cell twice within a single path.

Signature

// grid: string[][]   — a rectangular grid; each cell is a one-character string.
// word: string        — the target sequence of characters to spell.
// returns: boolean     — true iff `word` can be traced along a path of
//                        4-directionally adjacent cells, each used at most once.
function gridFindWord(grid: string[][], word: string): boolean;

Examples

// "ABCCED" weaves down and across the board; the two C's land on two
// different cells, so the path is valid.
const grid = [
  ['A', 'B', 'C', 'E'],
  ['S', 'F', 'C', 'S'],
  ['A', 'D', 'E', 'E'],
];
gridFindWord(grid, 'ABCCED'); // → true
// "ABCB" would need the single B at (0,1) twice. A cell can't be reused
// within one path, so there is no valid trace.
const grid = [
  ['A', 'B', 'C', 'E'],
  ['S', 'F', 'C', 'S'],
  ['A', 'D', 'E', 'E'],
];
gridFindWord(grid, 'ABCB'); // → false

Notes

  • Adjacency is 4-directional. From a cell you may move up, down, left, or right — never diagonally. Two letters that only touch at a corner are not connected.
  • Each cell is used at most once per path. The same cell cannot appear twice in the trace for one word, so 'aa' is impossible on a grid that holds a single 'a'.
  • Matching is case-sensitive. 'A' and 'a' are different letters; gridFindWord([['A']], 'a') is false.
  • Return a strict boolean. The result must be exactly true or false, not a truthy/falsy value like undefined or a cell.
  • Handle the empty and oversized cases. An empty grid returns false. A word with more characters than the grid has cells can never fit without reuse, so it returns false too.
  • Don't worry about multiple words. This is a single-word existence check — one word in, one boolean out.
Loading editor…