程序员面试金典 - 面试题 08.10. 颜色填充(BFS/DFS)

1. 题目

颜色填充。编写函数,实现许多图片编辑软件都支持的“颜色填充”功能。

给定一个屏幕(以二维数组表示,元素为颜色值)、一个点和一个新的颜色值,将新颜色值填入这个点的周围区域,直到原来的颜色值全都改变。

示例1:
 输入:
image = [[1,1,1],[1,1,0],[1,0,1]] 
sr = 1, sc = 1, newColor = 2
 输出:[[2,2,2],[2,2,0],[2,0,1]]
 解释: 
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。

说明:
image 和 image[0] 的长度在范围 [1, 50] 内。
给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length。
image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/color-fill-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 标准的广度和深度优先搜索,模板题

2.1 BFS

class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        int m = image.size(), n = image[0].size();
        int original = image[sr][sc], k, x, y, x0, y0;
        vector<vector<int>> dir = {{1,0},{0,1},{0,-1},{-1,0}};
        queue<vector<int>> q;
        vector<vector<bool>> visited(m, vector<bool>(n,false));
        q.push({sr,sc});
        visited[sr][sc] = true;
        image[sr][sc] = newColor;
        while(!q.empty())
        {
        	x0 = q.front()[0];
        	y0 = q.front()[1];
        	q.pop();
        	for(k = 0; k < 4; ++k)
        	{
        		x = x0+dir[k][0];
        		y = y0+dir[k][1];
        		if(x>=0 && x<m && y>=0 && y<n && !visited[x][y] && image[x][y]==original)
        		{
        			q.push({x,y});
        			visited[x][y] = true;
        			image[x][y] = newColor;
        		}
        	}
        }
        return image;
    }
};

在这里插入图片描述

2.2 DFS

class Solution {
	vector<vector<int>> dir = {{1,0},{0,1},{0,-1},{-1,0}};
	int m, n, original;
	vector<vector<bool>> visited;
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        m = image.size(), n = image[0].size();
        original = image[sr][sc];
        visited.resize(m, vector<bool>(n,false));
        visited[sr][sc] = true;
        image[sr][sc] = newColor;
        dfs(image,sr,sc,newColor);
        return image;
    }

    void dfs(vector<vector<int>>& image, int x0, int y0, int newColor)
    {
    	int x, y;
    	for(int k = 0; k < 4; ++k)
    	{
    		x = x0+dir[k][0];
    		y = y0+dir[k][1];
    		if(x>=0 && x<m && y>=0 && y<n && !visited[x][y] && image[x][y]==original)
    		{
    			visited[x][y] = true;
    			image[x][y] = newColor;
    			dfs(image,x,y,newColor);
    			//占领即可,不必回溯
    		}
    	}
    }
};

在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael阿明

如果可以,请点赞留言支持我哦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值