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, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
andword
consists of only lowercase and uppercase English letters.
-
GoLang
Runtime 375ms **Beats 25.83%**of users with Go
Memory 2.11MB **Beats 26.82%**of users with Go
func exist(board [][]byte, word string) bool { rows, cols := len(board), len(board[0]) visited := make(map[int]bool) var backtracking func(row, col int, target string) bool backtracking = func(row, col int, target string) bool { if row < 0 || row >= rows || col < 0 || col >= cols || visited[row*cols + col] || target[0] != board[row][col] { return false } target = target[1:len(target)] visited[row*cols + col] = true if target == "" { return true } isExisted := backtracking(row + 1, col, target) || backtracking(row - 1, col, target) || backtracking(row, col + 1, target) || backtracking(row, col - 1, target) visited[row*cols + col] = false return isExisted } for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { if backtracking(r, c, word) { return true } } } return false }