Skip to content

Commit 325e513

Browse files
halfrostdezhiy
authored andcommitted
Update 212 solution
1 parent f461ead commit 325e513

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

website/content/ChapterFour/0200~0299/0212.Word-Search-II.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,52 @@ func findWords(board [][]byte, words []string) []string {
5454
return res
5555
}
5656

57+
// these is 79 solution
58+
var dir = [][]int{
59+
{-1, 0},
60+
{0, 1},
61+
{1, 0},
62+
{0, -1},
63+
}
64+
65+
func exist(board [][]byte, word string) bool {
66+
visited := make([][]bool, len(board))
67+
for i := 0; i < len(visited); i++ {
68+
visited[i] = make([]bool, len(board[0]))
69+
}
70+
for i, v := range board {
71+
for j := range v {
72+
if searchWord(board, visited, word, 0, i, j) {
73+
return true
74+
}
75+
}
76+
}
77+
return false
78+
}
79+
80+
func isInBoard(board [][]byte, x, y int) bool {
81+
return x >= 0 && x < len(board) && y >= 0 && y < len(board[0])
82+
}
83+
84+
func searchWord(board [][]byte, visited [][]bool, word string, index, x, y int) bool {
85+
if index == len(word)-1 {
86+
return board[x][y] == word[index]
87+
}
88+
if board[x][y] == word[index] {
89+
visited[x][y] = true
90+
for i := 0; i < 4; i++ {
91+
nx := x + dir[i][0]
92+
ny := y + dir[i][1]
93+
if isInBoard(board, nx, ny) && !visited[nx][ny] && searchWord(board, visited, word, index+1, nx, ny) {
94+
return true
95+
}
96+
}
97+
visited[x][y] = false
98+
}
99+
return false
100+
}
101+
102+
57103
```
58104

59105

0 commit comments

Comments
 (0)