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
| func exist(board [][]byte, word string) bool { m := len(board) n := len(board[0]) chosen := make([][]bool, m) for i := 0; i < m; i++ { chosen[i] = make([]bool, n) } directions := [][]int{ {-1, 0}, {1, 0}, {0, -1}, {0, 1} } var backtrack func(x, y, begin int) bool backtrack = func(x, y, begin int) bool { if board[x][y] != word[begin] { return false } if begin == len(word)-1 { return true } chosen[x][y] = true for _, dirt := range directions { nextX := x + dirt[0] nextY := y + dirt[1] if nextX < 0 || nextX >= m || nextY < 0 || nextY >= n || chosen[nextX][nextY] { continue } if backtrack(nextX, nextY, begin+1) { return true } } chosen[x][y] = false
return false }
for i := 0; i < m; i++ { for j := 0; j < n; j++ { if backtrack(i, j, 0) { return true } } }
return false }
|