Web Toolbar by Wibiya

Pages

Saturday, July 2, 2011

Implement "Paint Fill" function used in paint.

Solution #1: Given a border separated region within a canvas, a "Paint Fill" function fills the region with a given color when the user clicks inside that region. Essentially we color all the pixels starting from the clicked pixel till we hit border all around. This is a classic recursion problem. The code below first implements a canvas of size=50x50 and then initializes it with Black color(1), creates a region within the canvas and fills it with white color(0) and then calls the "fill" function to fill this region with red color(5) recursively and finally prints the canvas.
enum
{
    WHITE = 0,
    BLACK = 1,
    RED = 5
};
void printCanvas(int canvas[][50], int canSize)
{
    int x,y;

    for(y=0; y < canSize; y++)
    {
        for(x=0; x < canSize; x++)
        {
            printf("%d ", canvas[y][x]);
        }
        printf("\n");
    }
    printf("\n");    
}

void createBorder(int canvas[][50])
{
    int x,y;

    for(y=5; y<45; y++)
    {
        for(x=5; x<45; x++)
        {
            canvas[y][x] = WHITE;
        }
    }
}

void init_canvas(int canvas[][50])
{
    
    int x,y;

    for(y=0; y<50; y++)
        for(x=0; x<50; x++)
            canvas[y][x] = BLACK;
}


void fill(int canvas[][50], int canSize, int x, int y)
{
    if(canvas == NULL)
        return;

    if(((x < canSize) && (x >= 0)) && ((y < canSize) && 
    (y >= 0)) && (canvas[x][y] != BLACK) && (canvas[x][y] == WHITE))
    {
        canvas[x][y] = RED;
        fill(canvas, canSize, x, y+1);
        fill(canvas, canSize, x, y-1);
        fill(canvas, canSize, x+1, y);
        fill(canvas, canSize, x-1, y);
    }
}


void main()
{
    int canvas[50][50] = {0,};

    init_canvas(canvas);
    createBorder(canvas);

    fill(canvas, 50, 25, 25);
    printCanvas(canvas, 50);
}

No comments: