Monday, September 14, 2020

Flood fill Algorithm

Problem: Given a 2D screen (matrix), location of a pixel in the screen and a color, replace color of the given pixel and all adjacent same colored pixels with the given color. (Like what MS Paint does for flood fill)

Approach: Use of recursion for every neighbor pixel.

        public void FloodFill(int[,] screen, int x, int y, int newColor)

        {

            int previousColor = screen[x, y];

            this.FloodFill(screen, x, y, previousColor, newColor);

        }


        private void FloodFill(int[,] screen, int x, int y, int previousColor, int newColor)

        {

            if (x < 0 || x >= screen.GetLength(0) || y < 0 || y >= screen.GetLength(1) || screen[x,y] != previousColor)

            {

                return;

            }

            screen[x, y] = newColor;

            this.FloodFill(screen, x - 1, y, previousColor, newColor);

            this.FloodFill(screen, x + 1, y, previousColor, newColor);

            this.FloodFill(screen, x, y - 1, previousColor, newColor);

            this.FloodFill(screen, x, y + 1, previousColor, newColor);

        } 

No comments:

Post a Comment