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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
package main
import ( "fmt" )
func exist(board [][]byte, word string) bool { if len(board) == 0 { return false }
rows, cols := len(board), len(board[0]) visited := make([][]bool, rows) for i := range visited { visited[i] = make([]bool, cols) }
var dfs func(r, c, index int) bool dfs = func(r, c, index int) bool { if index == len(word) { return true }
if r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] != word[index] { return false }
temp := board[r][c] board[r][c] = '#'
found := dfs(r+1, c, index+1) found = found || dfs(r-1, c, index+1) found = found || dfs(r, c+1, index+1) found = found || dfs(r, c-1, index+1)
board[r][c] = temp
return found }
for r := 0; r < rows; r ++ { for c := 0; c < cols; c ++ { if dfs(r, c, 0) { return true } } }
return false }
func main() { testCases := []struct { board [][]byte word string expected bool }{ { board: [][]byte{ {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}, }, word: "ABCCED", expected: true, }, { board: [][]byte{ {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}, }, word: "SEE", expected: true, }, { board: [][]byte{ {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}, }, word: "ABCB", expected: false, }, }
for i, tc := range testCases { fmt.Printf("Test Case %d, Input: board = [\n", i+1) for _, row := range tc.board { fmt.Printf("%v\n", row) } fmt.Printf("], word = %s\n", tc.word) result := exist(tc.board, tc.word)
if result == tc.expected { fmt.Printf("Test Case %d, Output: %v, PASS\n", i+1, result) } else { fmt.Printf("Test Case %d, Output: %v, FAIL (Expected: %v)\n", i+1, result, tc.expected) } } }
|