运行时错误:添加无符号偏移量溢出

问题描述

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 newColor) {
    int initial_value=image[sr][sc];
    image[sr][sc]=newColor;
    
    if(isSafe(image,sr+1,sc,initial_value))
    {
        // image[sr+1][sc]=newColor;
        image=floodFill( image,newColor);
    }
    if(isSafe(image,sr-1,sr,sc+1,sc-1,newColor);
    }
    return image;
}

};

解决方法

vector<vector<int>> floodFill(vector<vector<int>>& image,...

由于您是通过引用传递图像,因此无需按值返回。

使用后您将大大提高性能

void floodFill(vector<vector<int>>& image,int sr,int sc,int newColor) {
    int initial_value=image[sr][sc];
    image[sr][sc]=newColor;
    
    if(isSafe(image,sr+1,sc,initial_value))
    {
        floodFill( image,newColor);
    }
    if(isSafe(image,sr-1,sr,sc+1,sc-1,newColor);
    }
}