首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我在使用dfs算法时遇到运行时错误

我在使用dfs算法时遇到运行时错误
EN

Stack Overflow用户
提问于 2020-06-11 01:53:44
回答 1查看 68关注 0票数 0

在使用dfs解决问题时,我遇到了运行时错误。

下面是错误:

AddressSanitizer:堆栈溢出地址0x7ffce7e6eff8 (pc 0x000000359715 bp 0x7ffce7e6f040 sp 0x7ffce7e6f000 T0

以下是问题链接:

(https://leetcode.com/problems/flood-fill/)

下面是我的代码:

代码语言:javascript
复制
class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {

        int color=image[sr][sc];
        dfs(image,sr,sc,color,newColor);
        return image;
    }

    void dfs(vector<vector<int>> &image,int sr,int sc,int color,int newcolor)
    {
         if(sr<0 || sr>=image.size() || sc<0 || sc>=image[0].size() || image[sr][sc]!=color)
        {
            return;
        }

            image[sr][sc]=newcolor;
            dfs(image,sr,sc+1,color,newcolor);
            dfs(image,sr,sc-1,color,newcolor);
            dfs(image,sr+1,sc,color,newcolor);
            dfs(image,sr-1,sc,color,newcolor);

    }


};

它在以下测试用例中失败:

[0,0,0,0,1,1] 1 1 1

我想不出哪里出错了。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-14 03:34:15

检查newColor != color,否则会有无限递归,因为您依赖于颜色更改来避免重新访问以前访问过的像素。

这正是你失败的测试用例所发生的事情。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62309998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档