Problem · Matrix
MediumCognitiv logoCognitivFULLTIMEPHONE SCREEN

Problem statement

Given a rectangular character grid board and a string word, return true if word can be formed by a path through the grid. Otherwise, return false.

A path may move horizontally or vertically between adjacent cells. The same grid cell cannot be used more than once in one path.

Function

wordExists(board: char[][], word: String) → boolean

Examples

Example 1

board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]word = "ABCCED"return = true

The path uses the top-row cells A, B, and C, then continues down to C, left to E, and left to D.

Example 2

board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]word = "ABCB"return = false

The only adjacent B that could finish the word is the cell already used after the starting A, and a cell cannot be reused.

Example 3

board = [["A"]]word = "A"return = true

The single grid cell forms the complete word.

Constraints

  • 1 <= board.length <= 6
  • 1 <= board[i].length <= 6
  • Every row of board has the same length.
  • 1 <= word.length <= 15
  • board and word contain only uppercase and lowercase English letters.
drafts saved locally
public boolean wordExists(char[][] board, String word) {
  // Write your code here.
}
board[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]
word"ABCCED"
expectedtrue
checking account