Menu
CoddyTech

Word Search

You get a grid of letters board, given as a list of strings where board[r][c] is the letter in row r, column c, and a string word.

Return true if you can trace word on the grid: start on any cell, and each time step to the cell directly above, below, left or right of the current one, so that the cells you visit spell word in order. A tracing may not use the same cell twice. Otherwise return false. Letters are case sensitive, so a and A are different.

Function

exist(board: string-array, word: string) → boolean
boardstring-array
the grid, one string of letters per row
wordstring
the word to trace
Returnsboolean
whether word can be traced through side-by-side cells, each used at most once

Constraints

  • 1 ≤ board.length ≤ 6
  • 1 ≤ board[i].length ≤ 6, and every row has the same length.
  • 1 ≤ word.length ≤ 20
  • board and word contain only English letters, uppercase and lowercase.

Examples

Input
board = ["STAR", "POOL", "ENDS"]word = "STOOLS"
Output
true
Explanation
Start on the S at row 0, column 0, then go right to T, down to O, right to the second O, right to L, and down to the S at row 2, column 3. That is six different cells, each next to the one before it.

lock icon+23 hidden tests on Submit

challenge icon

Follow-up

Instead of yes or no, can you count how many different tracings of word the board holds?

Reset code
def exist(board, word):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

board = ["STAR", "POOL", "ENDS"]
word = "STOOLS"

Expected

true