搜索思想:DFS & BFS

  • DFS(Depth First Search)深度优先搜索
  • BFS(Breath First Search)广度优先搜索

就是两种暴力搜索去遍历所有的情况。

走迷宫来理解这两种搜索思想:

  1. DFS —— 先选择一个方向,然后遇到的每一个岔路,都继续走这个方向,直到此路不通(不通则返回上一个岔路重新选一个方向继续这样走)或走出迷宫。
  2. BFS —— 遇到岔路,向全部的方向先走一步(一步指遇到下一个岔路为止),每个方向都走完一步后,再从遇到的第一个岔路继续这样走,直到走出迷宫。(有人用水漫金山来形容BFS,还挺形象)

遍历二叉树来理解这两种搜索思想:

  1. DFS —— 前中后序遍历
  2. BFS —— 层序遍历
    在这里插入图片描述

通过解决 leetcode 733. 图像渲染,理解BFS与DFS思想。
在这里插入图片描述
【测试示例图示】
在这里插入图片描述

DFS

递归实现深度优先搜索

class Solution {
	//用来控制向上下左右移动( +dx[i], +dy[i])
    int[] dx = {1, 0, 0, -1};
    int[] dy = {0, 1, -1, 0};

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        // currColor = 当前颜色
        int currColor = image[sr][sc];
        if (currColor != newColor) {
            dfs(image, sr, sc, currColor, newColor);
        }
        return image;
    }

    public void dfs(int[][] image, int x, int y, int currcolor, int newColor) {
    	//满足条件
        if (image[x][y] == currcolor) {
            image[x][y] = newColor;
            // 遍历上下左右四个方向
            for (int i = 0; i < 4; i++) {
                int mx = x + dx[i], my = y + dy[i];
                // 保证(mx, my)在矩阵范围内
                if (mx >= 0 && mx < image.length && my >= 0 && my < image[0].length) {
                	// 递归
                    dfs(image, mx, my, currcolor, newColor);
                }
            }
        }
    }
}

BFS

队列实现广度优先搜索

class Solution {
	// 用来控制向上下左右移动( +dx[i], +dy[i])
    int[] dx = {1, 0, 0, -1};
    int[] dy = {0, 1, -1, 0};

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        // currColor = 当前颜色
        int currColor = image[sr][sc];
        // 与更新色相同就直接返回
        if (currColor == newColor) {
            return image;
        }
        // n, m为矩阵边界
        int n = image.length, m = image[0].length;
        Queue<int[]> queue = new LinkedList<int[]>();
        queue.offer(new int[]{sr, sc});
        image[sr][sc] = newColor;
        // 循环直到队列为空
        while (!queue.isEmpty()) {
        	// 出队列
            int[] cell = queue.poll();
            int x = cell[0], y = cell[1];
            // 遍历上下左右四个方向
            for (int i = 0; i < 4; i++) {
                int mx = x + dx[i], my = y + dy[i];
                // 0<= mx,my <=n/m 保证在矩阵范围内
                if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) {		
                // 加入队列并更新颜色
                    queue.offer(new int[]{mx, my});
                    image[mx][my] = newColor;
                }
            }
        }
        return image;
    }
}


感谢阅读 😉😉
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值