# 岛屿数量
给你一个由 1
(陆地)和 0
(水)组成的的二维网格,请你计算网格中岛屿的数量。
示例 1:
输入:grid = [ | |
["1","1","1","1","0"], | |
["1","1","0","1","0"], | |
["1","1","0","0","0"], | |
["0","0","0","0","0"] | |
] | |
输出:1 |
示例 2:
输入:grid = [ | |
["1","1","0","0","0"], | |
["1","1","0","0","0"], | |
["0","0","1","0","0"], | |
["0","0","0","1","1"] | |
] | |
输出:3 |
关键步骤已经注释出:
- 按顺序遍历二维数组,每次遍历时通过
dfs
函数搜索其上下左右位置 - 防止出边界的情况,提前计算好长、宽,及时
return
- 对访问过的位置进行标记,防止重复访问导致无法退出递归
- 搜索中遇到非
1
处即停止,这样保证一次搜出了一整块陆地,且不会被重复计数
func numIslands(grid [][]byte) int { | |
var ans int | |
m, n := len(grid), len(grid[0]) | |
var dfs func(r, c int) | |
dfs = func(r, c int) { | |
// 防止出边界 | |
if r < 0 || r >= m || c < 0 || c >= n { | |
return | |
} | |
// 非未访问过的陆地(水 or 已访问过的陆地) | |
if grid[r][c] != '1' { | |
return | |
} | |
// 标记已访问过的陆地:防止无限循环无法退出 | |
grid[r][c] = '2' | |
dfs(r-1, c) | |
dfs(r+1, c) | |
dfs(r, c-1) | |
dfs(r, c+1) | |
} | |
for r := 0; r < m; r++ { | |
for c := 0; c < n; c++ { | |
if grid[r][c] == '1' { | |
ans++ | |
dfs(r, c) | |
} | |
} | |
} | |
return ans | |
} |
# 单词搜索
给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word 存在于网格中,返回 true
;否则,返回 false
。
示例
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" | |
输出:true |
关键步骤已注释出:
- 保证边界问题
- 防止同次在重复位置搜索
found
变为true
的条件:之前的搜索都不被return
,直至最后一次下标值 = 长度 - 1 时仍匹配正确- 本题递归中带有回溯,因此要保证从每个点开始尝试搜索时,二维矩阵都回到初始状态,可以用
tmp
暂做记录,等待搜索结束后复原
func exist(board [][]byte, word string) bool { | |
m, n := len(board), len(board[0]) | |
found := false | |
var dfs func(r, c, k int) | |
dfs = func(r, c, k int) { | |
// 超出索引范围 | |
if r < 0 || c < 0 || r >= m || c >= n { | |
return | |
} | |
// 不能再走已经走过的 | |
if board[r][c] == '*' { | |
return | |
} | |
// 元素不相等 | |
if board[r][c] != word[k] { | |
return | |
} | |
// 找到了最后一个(元素相等) | |
if k == len(word)-1 { | |
found = true | |
return | |
} | |
// 标记走过 | |
tmp := board[r][c] | |
board[r][c] = '*' | |
// 往四周走试试 | |
dfs(r-1, c, k+1) | |
dfs(r+1, c, k+1) | |
dfs(r, c-1, k+1) | |
dfs(r, c+1, k+1) | |
// 回溯状态,便于下一点的验证 | |
board[r][c] = tmp | |
} | |
for r := 0; r < m; r++ { | |
for c := 0; c < n; c++ { | |
dfs(r, c, 0) | |
} | |
} | |
return found | |
} |