C++实现floodFill算法报无符号偏移溢出运行时错误求解
floodFill算法报错分析与修复方案
报错原因
- 核心笔误:第四个方向(向左遍历,对应
sc-1)的递归参数传递错误。你在isSafe中验证的是坐标(sr, sc-1)的合法性,但实际递归调用时传入了sr-1和sc,相当于未验证sr-1的合法性就直接访问该下标。当sr为0时,sr-1为负数,C++中vector的下标是无符号类型,负数转为无符号数会变成极大值,计算内存偏移时就会触发无符号偏移溢出的运行时错误。 - 边界场景遗漏:如果传入的
newColor和初始像素值initial_value相等,代码会陷入无限递归:你将当前像素设为newColor后和原值一致,相邻节点递归时会再次判定当前像素符合填充条件,重复发起递归,最终要么栈溢出要么触发下标偏移溢出。
修复方案
按以下步骤修改即可:
- 修正第四个方向的递归参数,传入正确的
sr和sc-1 - 函数开头增加判断:如果新颜色和初始颜色相等,直接返回原图像,避免无效递归
- (可选优化)无需对
image重复赋值,因为参数是引用类型,递归修改会直接作用在原对象上
修复后完整代码
class Solution { public: bool isSafe(vector<vector<int>> &image, int sr, int sc, int initial_value){ if(sr>=0 && sr<image.size() && sc>=0 && sc<image[0].size() && image[sr][sc]==initial_value) { return true; } return false; } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int initial_value = image[sr][sc]; // 新增:新旧颜色相同直接返回 if (initial_value == newColor) { return image; } image[sr][sc] = newColor; if(isSafe(image, sr+1, sc, initial_value)) { floodFill(image, sr+1, sc, newColor); } if(isSafe(image, sr-1, sc, initial_value)) { floodFill(image, sr-1, sc, newColor); } if(isSafe(image, sr, sc+1, initial_value)) { floodFill(image, sr, sc+1, newColor); } if(isSafe(image, sr, sc-1, initial_value)) { // 修正:传入正确的坐标 floodFill(image, sr, sc-1, newColor); } return image; } };
内容的提问来源于stack exchange,提问作者Nachiket Punjabi
相关产品推荐
相关产品推荐

