Now, let's turn our attention to a totally different problem. We are working on a 2D drawing package, and we want to make a bucket fill tool similar to that found in Microsoft Paint. The user selects a color, clicks on a point, and the color spreads to fill the area with this color. Have a look at this figure.
Fig 2. We need to write a program to flood fill a shape We want to write a function to implement this feature. We are given a 2 dimensional array of colors, a point to start painting from, and a color. We should fill the fill area with the color as mentioned above. There is no easy non-recursive solution to this problem, but we can solve this recursively in just 8 lines of code. How? The idea is simply to make a flood fill from a point do the following:
Now, you see, the whole solution is just 5 steps, and 4 of them are recursive calls. It is important to understand how this actually works.
I have tried to make the code simpler by fixing width and height. But, of course, it is easy to generalize the code to different sizes and color formats.
blog comments powered by Disqus |