Description

Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells (horizontally or vertically). The same cell may not be used more than once.

Examples

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

Starting at (0,0)='A', move right to (0,1)='B', right to (0,2)='C', down to (1,2)='C', down to (2,2)='E', left to (2,1)='D'. The path A→B→C→C→E→D spells 'ABCCED' using only adjacent cells without reusing any cell.

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

Starting at (0,0)='A', move right to (0,1)='B', right to (0,2)='C'. To spell 'ABCB', it is needed to another 'B', but the only 'B' at (0,1) was already used. Since cells cannot be reused in the same path, 'ABCB' cannot be formed.

Input:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output:true
Explanation:

Starting at (1,3)='S', move down to (2,3)='E', left to (2,2)='E'. The path S→E→E at positions (1,3)→(2,3)→(2,2) spells 'SEE' using adjacent cells. Each cell is used exactly once.

Constraints

  • m == board.length
  • n == board[i].length
  • 1 ≤ m, n ≤ 6
  • 1 ≤ word.length ≤ 15
  • board and word consists of only lowercase and uppercase English letters.

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!