題目: 編寫函數,實現許多圖片編輯軟件都支持的「顏色填充」功能。
待填充的圖像用二維數組 image 表示,元素爲初始顏色值。初始座標點的橫座標爲 sr 縱座標爲 sc。需要填充的新顏色爲 newColor 。周圍區域」是指顏色相同且在上、下、左、右四個方向上存在相連情況的若干元素。
請用新顏色填充初始座標點的周圍區域,並返回填充後的圖像。
示例:
輸入:
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] 內。
- 初始座標點 (sr,sc) 滿足 0 <= sr < image.length 和 0 <= sc < image[0].length 。
- image[i][j] 和 newColor 表示的顏色值在範圍 [0, 65535] 內。
相關題目:
思路: 經典DFS搜索即可:
- 從給定的位置開始搜索,上,下,左,右不斷回溯搜索。
- 越過邊界或搜索完畢退出。
示例的塗染過程:
DFS思路在兩個相關題目中有詳細的闡述,這裏就不再說了。
1. 自己寫的,處理太過冗餘:
void dp(vector<vector<int>>& image, int sr, int sc, int newColor,int temp)
{
if(image[sr][sc]==temp)
return;
//上
if((sr-1)>=0 && (sr-1)<image.size() && sc>=0 && sc< image[0].size() && image[sr-1][sc]==temp)
{
image[sr-1][sc]=newColor;
dp(image,sr-1,sc,newColor,temp);
}
//下
if((sr+1)>=0 && (sr+1)<image.size() && sc>=0 && sc< image[0].size() && image[sr+1][sc]==temp)
{
image[sr+1][sc]=newColor;
dp(image,sr+1,sc,newColor,temp);
}
//左
if((sr)>=0 && (sr)<image.size() && (sc-1)>=0 && (sc-1)< image[0].size() && image[sr][sc-1]==temp)
{
image[sr][sc-1]=newColor;
dp(image,sr,sc-1,newColor,temp);
}
//右
if((sr)>=0 && (sr)<image.size() && (sc+1)>=0 && (sc+1)< image[0].size() && image[sr][sc+1]==temp)
{
image[sr][sc+1]=newColor;
dp(image,sr,sc+1,newColor,temp);
}
return;
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor)
{
int temp=image[sr][sc];
image[sr][sc]=newColor;
dp(image,sr,sc,newColor,temp);
return image;
}
2. 參考別人重新寫的:
void dp(vector<vector<int>>& image, int sr, int sc, int newColor,int temp)
{
if((sr)<0 || sr>=image.size() || sc<0 || sc>= image[0].size())
{
return;
}
if(image[sr][sc]==temp)
{
image[sr][sc]=newColor;
dp(image,sr-1,sc,newColor,temp);//上
dp(image,sr+1,sc,newColor,temp);//下
dp(image,sr,sc-1,newColor,temp);//左
dp(image,sr,sc+1,newColor,temp);//右
}
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor)
{
if(image[sr][sc]==newColor)
return image;
int temp=image[sr][sc];
dp(image,sr,sc,newColor,temp);
return image;
}
int main() //主函數測試
{
vector<vector<int>>image;
vector<int> temp;
temp.push_back(0);
temp.push_back(0);
temp.push_back(0);
image.push_back(temp);
temp.clear();
temp.push_back(0);
temp.push_back(1);
temp.push_back(1);
image.push_back(temp);
image=floodFill(image,1,1,1);
for(int i=0;i<image.size();i++)
{
for(int j=0;j<image[i].size();j++)
{
cout<<image[i][j];
}
cout<<endl;
}
}
加油哦!💪。