From 8955e6a88b112da2c4a1272456548b74aeb94dc6 Mon Sep 17 00:00:00 2001 From: Umesh Kumar <56982559+Umesh-JNU@users.noreply.github.com> Date: Sun, 10 Oct 2021 11:23:00 +0530 Subject: [PATCH] Added the Flood-fill algorithm --- Flood_Fill.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Flood_Fill.cpp diff --git a/Flood_Fill.cpp b/Flood_Fill.cpp new file mode 100644 index 0000000..4fbcdd9 --- /dev/null +++ b/Flood_Fill.cpp @@ -0,0 +1,58 @@ +/* + * Author : Umesh Kumar + * Date : 06/10/2021 + * Problem : https://leetcode.com/problems/flood-fill/ + */ +#include +#include +using namespace std; + +void dfs(vector> &img, int sr, int sc, int src, int newColor) +{ + if (img[sr][sc] != src) + return; + + img[sr][sc] = newColor; + // top + if (sr - 1 >= 0) + dfs(img, sr - 1, sc, src, newColor); + // bottom + if (sr + 1 < img.size()) + dfs(img, sr + 1, sc, src, newColor); + // left + if (sc - 1 >= 0) + dfs(img, sr, sc - 1, src, newColor); + // right + if (sc + 1 < img[0].size()) + dfs(img, sr, sc + 1, src, newColor); +} +vector> floodFill(vector> &image, int sr, int sc, int newColor) +{ + // if src == newColor, then all the associated grid will of same then no change + if (image[sr][sc] == newColor) + return image; + dfs(image, sr, sc, image[sr][sc], newColor); + return image; +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + cout.tie(nullptr); + vector> image = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}; + int sr = 1, sc = 1, newColor = 2; + for (auto e : floodFill(image, sr, sc, newColor)) + { + for (auto a : e) + cout << a << " "; + cout << endl; + } + image = {{0, 0, 0}, {0, 0, 0}}, sr = 0, sc = 0, newColor = 2; + for (auto e : floodFill(image, sr, sc, newColor)) + { + for (auto a : e) + cout << a << " "; + cout << endl; + } + return 0; +} \ No newline at end of file