栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【LeetCode-简单】733. 图像渲染 - DFS/BFS

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【LeetCode-简单】733. 图像渲染 - DFS/BFS

733. 图像渲染

解法一:BFS
从给定的起点开始,进行广度优先搜索。每次搜索到一个方格时,如果其与初始位置的方格颜色相同,就将该方格加入队列,并将该方格的颜色更新,以防止重复入队。

注意:因为初始位置的颜色会被修改,所以需要保存初始位置的颜色,以便于之后的更新操作。

class Solution {
public:
    const int dx[4]={0,1,0,-1};
    const int dy[4]={1,0,-1,0};
    vector> floodFill(vector>& image, int sr, int sc, int newColor) {
        int curcolor=image[sr][sc];
        if(newColor==curcolor) return image;
        int n=image.size(), m=image[0].size();
        queue> que;
        que.emplace(sr, sc);
        image[sr][sc]=newColor;
        while (!que.empty()) {
            int x = que.front().first, y = que.front().second;
            que.pop();
            for (int i=0;i<4;i++) {
                int mx=x+dx[i], my=y+dy[i];
                if (mx>=0 && mx=0 && my 

C++ pair的基本用法总结

emplace操作是C++11新特性,新引入的的三个成员emplace_front、emplace 和 emplace_back。这些操作构造而不是拷贝元素到容器中,这些操作分别对应push_front、insert和push_back,允许我们将元素放在容器头部、一个指定的位置和容器尾部。

两者的区别:当调用insert时,是将对象传递给insert,对象被拷贝到容器中,而当我们使用emplace时,是将参数传递给构造函,emplace使用这些参数在容器管理的内存空间中直接构造元素。

解法二:DFS
从给定的起点开始,进行深度优先搜索。每搜索到一个方格,如果其与初始位置的方格颜色相同,就将该方格的颜色更新,以防止重复搜索;如果不相同,则进行回溯。

同样,由于初始位置的颜色会被修改,所以需要保存初始位置的颜色,以便于之后的更新操作。

class Solution {
public:
    vector> floodFill(vector>& image, int sr, int sc, int newColor) {
        int color=image[sr][sc];
	    if (color==newColor) return image;
	    if (sr>=0 && sr=0 && sc 

力扣给出的题解代码如下:

class Solution {
public:
    const int dx[4] = {1, 0, 0, -1};
    const int dy[4] = {0, 1, -1, 0};
    vector> floodFill(vector>& image, int sr, int sc, int newColor) {
        int curcolor = image[sr][sc];
        if (curcolor != newColor) {
            dfs(image, sr, sc, curcolor, newColor);
        }
        return image;
    }
    void dfs(vector>& image, int x, int y, int color, int newColor) {
        if (image[x][y] == color) {
            image[x][y] = newColor;
            for (int i = 0; i < 4; i++) {
                int mx=x+dx[i], my=y+dy[i];
                if (mx>=0 && mx=0 && my
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/630571.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号