Files
interview/16-LeetCode Hot 100/单词搜索.md
yasinshaw 4247e0700d refactor: convert all LeetCode solutions to Go-only
Changes:
- Removed all Java code implementations
- Kept only Go language solutions
- Renamed "## Go 解法" to "## 解法"
- Removed "### Go 代码要点" sections
- Cleaned up duplicate headers and empty sections
- Streamlined documentation for better readability

Updated files (9):
- 三数之和.md
- 两数相加.md
- 无重复字符的最长子串.md
- 最长回文子串.md
- 括号生成.md
- 子集.md
- 单词搜索.md
- 电话号码的字母组合.md
- 柱状图中最大的矩形.md

All 22 LeetCode Hot 100 Medium problems now use Go exclusively.
Code is cleaner, more focused, and easier to follow.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2026-03-05 12:32:55 +08:00

115 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 单词搜索 (Word Search)
## 题目描述
给定一个 `m x n` 二维字符网格 `board` 和一个字符串单词 `word`。如果 `word` 存在于网格中,返回 `true`;否则,返回 `false`
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中"相邻"单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
### 示例
**示例 1**
```
输入board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出true
```
**示例 2**
```
输入board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出true
```
**示例 3**
```
输入board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出false
```
## 解题思路
### 方法一DFS + 回溯(推荐)
**核心思想:**对每个位置进行 DFS搜索是否存在匹配的单词路径。
**算法步骤:**
1. 遍历网格的每个位置
2. 如果当前位置字符匹配单词首字符,开始 DFS
3. DFS 过程中:
- 标记当前已访问
- 向四个方向递归搜索
- 如果找到完整单词,返回 true
- 回溯时撤销访问标记
## 代码实现
### Go 实现
```go
package main
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 dfs func(i, j, k int) bool
dfs = func(i, j, k int) bool {
// 找到完整单词
if k == len(word) {
return true
}
// 边界检查或不匹配
if i < 0 || i >= m || j < 0 || j >= n ||
visited[i][j] || board[i][j] != word[k] {
return false
}
// 标记访问
visited[i][j] = true
// 向四个方向搜索
found := dfs(i+1, j, k+1) ||
dfs(i-1, j, k+1) ||
dfs(i, j+1, k+1) ||
dfs(i, j-1, k+1)
// 回溯:取消标记
visited[i][j] = false
return found
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if board[i][j] == word[0] && dfs(i, j, 0) {
return true
}
}
}
return false
}
```
**LeetCode 212:** 给定一个 m x n 二维字符网格 board 和一个单词列表 words返回所有在二维网格和字典中出现的单词。
```go
func findWords(board [][]byte, words []string) []string {
// 构建 Trie 树
trie := buildTrie(words)
result := []string{}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[0]); j++ {
dfsBoard(board, i, j, trie, &result)
}
}
return result
}
```