Skip to content

Commit 96fd61b

Browse files
aQuaaQua
aQua
authored and
aQua
committed
79 finish
1 parent b998496 commit 96fd61b

File tree

2 files changed

+12
-20
lines changed

2 files changed

+12
-20
lines changed

Algorithms/0079.word-search/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,6 @@ word = "ABCB", -> returns false.
2424

2525
## 解题思路
2626

27+
使用dfs
28+
2729
见程序注释

Algorithms/0079.word-search/word-search.go

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,34 +15,24 @@ func exist(board [][]byte, word string) bool {
1515
return false
1616
}
1717

18-
delta := [][2]int{
19-
[2]int{0, -1},
20-
[2]int{0, 1},
21-
[2]int{-1, 0},
22-
[2]int{1, 0},
23-
}
24-
25-
var dfs func(int, int, string) bool
26-
dfs = func(r, c int, word string) bool {
27-
if len(word) == 0 {
18+
var dfs func(int, int, int) bool
19+
dfs = func(r, c, index int) bool {
20+
if len(word) == index {
2821
return true
2922
}
3023

31-
if r < 0 || m <= r || c < 0 || n <= c {
32-
return false
33-
}
34-
35-
if board[r][c] != word[0] {
24+
if r < 0 || m <= r || c < 0 || n <= c || board[r][c] != word[index] {
3625
return false
3726
}
3827

3928
temp := board[r][c]
4029
board[r][c] = 0
4130

42-
for _, d := range delta {
43-
if dfs(r+d[0], c+d[1], word[1:]) {
44-
return true
45-
}
31+
if dfs(r-1, c, index+1) ||
32+
dfs(r+1, c, index+1) ||
33+
dfs(r, c-1, index+1) ||
34+
dfs(r, c+1, index+1) {
35+
return true
4636
}
4737

4838
board[r][c] = temp
@@ -52,7 +42,7 @@ func exist(board [][]byte, word string) bool {
5242

5343
for i := 0; i < m; i++ {
5444
for j := 0; j < n; j++ {
55-
if dfs(i, j, word) {
45+
if dfs(i, j, 0) {
5646
return true
5747
}
5848
}

0 commit comments

Comments
 (0)