MediumBacktrackingRecursionMatrix

Word Search

LeetCode
1 approach, code in all languages

You are given a grid of characters with m rows and n columns along with a target word. Decide whether the word can be traced through the grid by moving between cells that share an edge, that is up, down, left, or right. The path must spell the word in order and may not reuse the same cell more than once.

Return true if such a path exists anywhere in the grid, and false otherwise. Diagonal moves are not allowed.

Example 1

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"

Output: true

Starting at the top-left A, the path A to B to C to C to E to D stays adjacent and reuses no cell.

Example 2

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"

Output: false

Reaching the final B would require stepping back onto the already-used B cell, which is not allowed.

Constraints

  • 1 <= board.length, board[0].length <= 6
  • 1 <= word.length <= 15
  • board and word contain only English letters
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now