題目: LeetCode - 733. Flood Fill

題目說明

給一個二維的陣列當作 2d 圖片,陣列裡面的元素代表該座標的顏色,給一個座標及一個 newColor 做填滿顏色的動作 ( 與小畫家的 填入色彩 類似)。

解題思路

先判斷舊顏色和新顏色是否相同,若相同就直接回傳 image,否則就從該點使用遞迴的概念替換顏色即可。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
void fill(vector<vector<int>>& image, int i, int j, int oldColor, int newColor, int height, int width)
{
if(i < 0 || j < 0 || i >= height || j >= width || image[i][j] != oldColor)
return;
image[i][j] = newColor;
fill(image, i + 1, j, oldColor, newColor, height, width);
fill(image, i - 1, j, oldColor, newColor, height, width);
fill(image, i, j + 1, oldColor, newColor, height, width);
fill(image, i, j - 1, oldColor, newColor, height, width);
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(image[sr][sc] == newColor)
return image;
int height = image.size(), width = image[0].size();
fill(image, sr, sc, image[sr][sc], newColor, height, width);
return image;
}
};