/79. Word Search

79. Word Search

Medium
Arrays47% acceptance

Given a 2D list of characters grid and a string target, return True if target can be formed by sequentially adjacent cells in grid. Adjacent cells are horizontally or vertically neighboring. Each cell can be used at most once in the path.

Example 1

Input: grid = [[X,Y,Z],[A,B,C],[D,E,F]], target = XYZ

Output: True

Explanation: The path X->Y->Z exists horizontally in the first row.

Example 2

Input: grid = [[M,N,O],[P,Q,R],[S,T,U]], target = MNPQ

Output: False

Explanation: No valid path forms MNPQ without reusing cells.

Example 3

Input: grid = [[A,B],[C,D]], target = ACBD

Output: False

Explanation: Cannot form ACBD as B and D are not adjacent to C.

Constraints

  • 1 <= len(grid) <= 6
  • 1 <= len(grid[0]) <= 6
  • 1 <= len(target) <= 15
  • grid and target consist of only lowercase and uppercase English letters
Python (current runtime)

Case 1

Input: grid = [['H','I','J'],['K','L','M'],['N','O','P']], target = 'HIKL'

Expected: True

Case 2

Input: grid = [['Q','R','S'],['T','U','V'],['W','X','Y']], target = 'QRTU'

Expected: True

Case 3

Input: grid = [['A','B','C'],['D','E','F'],['G','H','I']], target = 'AEI'

Expected: False

Case 4

Input: grid = [['Z','Y','X'],['W','V','U'],['T','S','R']], target = 'ZYXWVUTSR'

Expected: True

Case 5

Input: grid = [['A','B'],['C','D']], target = 'ABCD'

Expected: False