基础知识
存储方式
- 朴素:n*2数组表示
- 邻接矩阵:n*n数组
- 邻接表:数组加链表
DFS:递归模板
1 2 3 4 5 6 7 8 9 10 11 12
| void dfs(参数) { if (终止条件) { 存放结果; return; }
for (选择:本节点所连接的其他节点) { 处理节点; dfs(图,选择的节点); 回溯,撤销处理结果 } }
|
注意很多终止条件可以在递归前加判断,有效减少了多一层递归。
BFS:队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| func bfs(grid byte, visited bool, x, y int) { queue := make(int, 0) queue = append(queue, int{x, y}) visited = true for len(queue) != 0 { x := queue y := queue queue = queue for i := 0; i < 4; i++ { nextx := x + direction nexty := y + direction if nextx < 0 || nextx >= len(grid) || nexty < 0 || nexty >= len(grid) { continue } if !visited { queue = append(queue, int{nextx, nexty}) visited = true } } } }
|
岛屿数量
双重for循环对每个点进行检查
dfs是采用递归来往下搜索,而bfs是用队列来控制搜索
本质是对每个点都尝试进行检查和搜索,然后搜索后汇聚形成答案。