1.5 深度优先搜索 DFS(LC:938 + 200)
DFS:
- 主要思想:递归思想
- 搜索顺序:从树状图中的根节点root开始,尽可能深的搜索每一个分支(把一个分支的结果搜索完后,才会进行回溯到上一层,然后再去搜索下一个分支)
- 主要应用:
- 图搜索
- 二叉树搜索
二叉树的递归(使用DFS)代码雏形(根据题目要求,在本代码的基础上进行增加和修改):
public void dfs(root):
if(root == null){
return;
}
dfs(root.left);
dfs(root.right);
DFS和回溯法的区别:
- 回溯算法 = DFS + 剪枝
- DFS:一定要搜索到每个分支的最深层
- 回溯算法:不需要搜索到每个分支的最深层,只要满足搜索的深度了,就可以返回到上一层了
个人理解:
回溯就是一种从深层递归回到浅层递归的过程,在图示中就是从树状图的深层回到浅层的过程。因此DFS中也可以认为包含了回溯这个过程
938. 二叉搜索树的范围和 - 力扣(LeetCode) (leetcode-cn.com)
难度:简单
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例 1:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
解释:10、7、15在[7,15]内,3、5<7、18>15,均不在[7,15]内
示例 2:
输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
输出:23
提示:
树中节点数目在范围 [1, 2 * 104] 内
1 <= Node.val <= 105 1 <= low <= high <= 105
所有 Node.val 互不相同
思路:
二叉搜索树:一个节点的左孩子节点一定比该节点小,右孩子节点一定比该节点大
解法1:递归
对于每个节点,将其分成该节点、左孩子节点、右孩子节点,判断这3个节点的值是否在范围内,如果在,直接加到res中,然后针对左孩子节点和右孩子节点,继续这一操作
计算res的公式:res = 左孩子节点的值(如果满足范围条件) + 右孩子节点的值(如果满足范围条件) + 该节点本身的值(如果满足范围条件)
图示:
递归的终止条件:
递归到的节点 == null
解法2:BFS
BFS一般和队列组合使用
对每一层节点进行出队操作,边出队边边判断是否满足范围条件,同时添加下一层节点入队
代码:
解法1:递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
int res = 0;
res = recursion(root, low, high, res);
return res;
}
//注意:每一步必须要返回res的值,否则下一层递归中res的值无法得到保存,因为会被上一层递归中传入的参数res覆盖
//为什么这里的res会有被覆盖的问题呢?
//原因:这里的res是基本数据类型,在值传递时传递的是真实数据值,相当于拷贝了一份,在修改下一层的res时,无法修改上一层的res,所以会被上一层的res覆盖
// 其他题中的res是引用数据类型,在值传递时传递的是地址值,如果递归中某一层的res被修改,则所有层的res都会被修改
private int recursion(TreeNode root, int low, int high, int res){
//递归的终止条件
if(root == null){
return 0;
}
//对左右孩子节点分别进行递归操作
int leftSum = recursion(root.left, low, high, res); //进入该递归时,左孩子节点root.left就充当了root
int rightSum = recursion(root.right, low, high, res); //进入该递归时,右孩子节点root.right就充当了root
//需要将左右孩子节点满足条件的值相加作为res,此时只差root节点本身的值
res = leftSum + rightSum;
if(root.val >= low && root.val <= high){
res += root.val;
}
return res;
}
}
关于java的方法参数传递机制中,基本数据类型值传递的演示:
public static void main(String[] args) {
int a = 0;
test1(a);
System.out.println(a); //0
a = test2(a);
System.out.println(a); //5
}
public static void test1(int b){
b += 5;
}
public static int test2(int b){
b += 5;
return b;
}
解法2:BFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
int res = 0;
Queue<TreeNode> queue = new LinkedList<>(); //注意类型是TreeNode,不是Integer
queue.add(root);
//如果队列的长度=0,则说明该树遍历结束了,或者该树不存在
while(queue.size() > 0){
//这个size记录的是每层节点的个数(假设为第i层),目的是在下面的while循环中,将队列queue中第i层的节点全部出队,第i+1层的节点全部入队,在下面的while结束时,队列中只剩下第i+1层节点
int size = queue.size();
//这个while循环是BFS的精髓,体现出第i层搜索结束后,才会搜索第i+1层
while(size > 0){
TreeNode temp = queue.poll(); //注意temp是TreeNode类型,不是int类型
if(temp.val >= low && temp.val <= high){
res += temp.val;
}
if(temp.left != null){
queue.add(temp.left);
}
if(temp.right != null){
queue.add(temp.right);
}
size--;
}
}
return res;
}
}
200. 岛屿数量 - 力扣(LeetCode) (leetcode-cn.com)
难度:中等
给你一个由 '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
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 '0' 或 '1'
思路:
解法1:DFS
遍历二维数组,对于数组中为'1'的每个节点,使用DFS递归搜索该节点周围的4个节点,如果有'1',则改写成'0',并且继续使用DFS递归搜索该节点周围节点值为'1'的周围节点
递归的终止条件:
节点值为'0'或者节点超出了数组范围
解法2:BFS
辨析DFS和BFS在本题中的区别:
- DFS:对于元素值为'1'的节点(x,y),搜索其周围的4个节点,直到满足递归条件时终止递归,没有回溯的过程(这是一种递归到最深处的DFS思想)
- BFS:对于元素值为'1'的节点(x,y),将(x,y)作为第i层节点,将其周围的4个节点中满足条件的节点作为第i+1层节点,先将第i层节点出队,同时入队第i+1层节点(这是每一层搜索结束再进行下一层的BFS思想)
一个细节点:
为了避免重复搜索,需要将已经搜索过的、元素值为'1'的节点,更新为'0'
代码:
解法1:DFS
class Solution {
public int numIslands(char[][] grid) {
int res = 0; //存放岛屿的数量
int row = grid.length; //数组的行数
int column = grid[0].length; //数组的列数
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
if(grid[i][j] == '1'){
res++; //元素是'1',则说明该点是岛屿或者是岛屿的一部分,然后进入bfs,判断该点周围相邻的4个点是否还有元素'1',如果有则改写成'0'(因为是连在一起的,所以都是1个岛屿)
dfs(grid, i, j, row, column);
}
}
}
return res;
}
private void dfs(char[][] grid, int i, int j, int row, int column){
//递归的终止条件:当扫描的点不在数组范围内,或者扫描的点的元素是'0'
if(i < 0 || j < 0 || i >= row || j >= column || grid[i][j] == '0'){
return;
}
grid[i][j] = '0';
//进行递归扫描坐标(i, j)周围的4个点是否是'1'
dfs(grid, i + 1, j, row, column);
dfs(grid, i - 1, j, row, column);
dfs(grid, i, j + 1, row, column);
dfs(grid, i, j - 1, row, column);
}
}
解法2:BFS
class Solution {
public int numIslands(char[][] grid) {
int res = 0; //存放岛屿的数量
Queue<int[]> queue = new LinkedList<>(); //因为入队的是元素的坐标,坐标是由2个int类型元素构成的,所以queue中的元素类型是int[]数组类型
int row = grid.length; //数组的行数
int column = grid[0].length; //数组的列数
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
if(grid[i][j] == '1'){
res++;
queue.add(new int[]{i,j});
grid[i][j] = '0';
while(queue.size() > 0){
int size = queue.size();
while(size > 0){
int[] temp = queue.poll(); //temp是数组类型
int x = temp[0]; //出队元素的横坐标
int y = temp[1]; //出队元素的纵坐标
//下面的4个if,就是判断点(x,y)周围的4个节点的值是否为'1',需要注意的是,周围4个节点的坐标不能超出数组范围,所以需要加上限制条件
if(x + 1 < row && grid[x + 1][y] == '1'){
queue.add(new int[]{x + 1,y});
grid[x + 1][y] = '0';
}
if(x - 1 >= 0 && grid[x - 1][y] == '1'){
queue.add(new int[]{x - 1,y});
grid[x - 1][y] = '0';
}
if(y + 1 < column && grid[x][y + 1] == '1'){
queue.add(new int[]{x,y + 1});
grid[x][y + 1] = '0';
}
if(y - 1 >= 0 && grid[x][y - 1] == '1'){
queue.add(new int[]{x,y - 1});
grid[x][y - 1] = '0';
}
size--;
}
}
}
}
}
return res;
}
}