Color filling in MS-Paint

#include <stdio.h>

typedef struct Pixel
{
/*Pixel coordinates*/
int x, y;

}Pixel;

typedef Pixel Direction;

typedef struct Matrix
{
/*numrows x numcolumns*/
int m, n;

/*flattened two dimensional array*/
int *a;

}Matrix;


void fillcolor(Matrix m, int color, Pixel p)
{
static const Direction directions[8] = { {-1, 0}, {1, 0}, {0, 1}, {0, -1},
{1, 1}, {1, -1}, {-1, 1},{-1, -1}
};

/*flattened index*/
int index = p.x *m.n + p.y;

/*current color of the pixel*/
int val = m.a[index];

/*change the color of the pixel to the given*/
m.a[index] = color;

int i, j, d;

Pixel temp;

/*Fill all the connected pixels*/
for(d = 0; d < 8; d++)
{
i = directions[d].x;
j = directions[d].y;

temp.x = p.x + i;
temp.y = p.y + j;

/*Check boundaries*/
if(temp.x < 0 || temp.x >= m.m) continue;
if(temp.y < 0 || temp.y >= m.n) continue;

/*Check the color of this pixel*/
if(m.a[temp.x * m.n + temp.y] != val) continue;

fillcolor(m, color, temp);
}

}

int main()
{
int a[][4] = {1, 0, 2, 0,
0, 2, 0, 2,
2, 0, 2, 1
};

Matrix m = {3, 4, (int *)a};

Pixel p = {2, 1};

fillcolor(m, 3, p);

int i, j;

for(i = 0 ; i < 3; ++i)
{
for(j = 0; j < 4; ++j)
printf("%d ", a[i][j]);

printf("\n");
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s