1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| var directions = [][]int{ {1, 0}, {0, 1}, {-1, 0}, {0, -1}, }
func exist(board [][]byte, word string) bool { m, n := len(board), len(board[0]) visited := make([][]bool, m) for i := range visited { visited[i] = make([]bool, n) }
var backtrack func(i, j, curr int) bool backtrack = func(i, j, curr int) bool { if board[i][j] != word[curr] { return false } if curr == len(word)-1 { return true }
visited[i][j] = true defer func(){ visited[i][j] = false }()
for _, d := range directions { nextI, nextJ := i+d[0], j+d[1] if nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n && !visited[nextI][nextJ] { if backtrack(nextI, nextJ, curr+1) { return true } } }
return false }
for i := range visited { for j := range visited[i] { if backtrack(i, j, 0) { return true } } }
return false }
|