CodePark/ problems / Find the Word in the Grid
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Backtracking

Find the Word in the Grid

mediumabout 25 minutes in an interview

You get a grid of capital letters, grid[row][col], and a word. Return true if you can spell the word by moving from cell to cell. Otherwise return false.

  • You may start on any cell.
  • Each next letter must be in a cell that touches the previous cell up, down, left or right. Diagonal moves are not allowed.
  • The word may use each cell at most once.
  • The grid is between 1 × 1 and 6 × 6. Every row has the same length. Every cell holds one letter from A to Z.
  • word has 1 to 12 capital letters.
  • When your function returns, grid must look exactly as it did before the call. If you change cells while you search, put them back.
Input: grid = [["D", "O", "G", "S"], ["A", "R", "E", "A"], ["M", "O", "L", "T"]], word = "ROLE" Output: trueR (1,1) → O (2,1) → L (2,2) → E (1,2). The O above R is a dead end.
Input: same grid, word = "DOOR" Output: falseThe two O cells don't touch each other.
Input: grid = [["A", "B"]], word = "ABA" Output: falseThe second A would need to use the first cell again.