Monday, 16 March 2015

Polygon Filling with Non recursive

#include<stdio.h>
#include<graphics.h>
struct stack
{
 long int x;
 long int y;
 struct stack *next;
}*p,*temp,*head=NULL;

typedef struct stack t1;
void push(int,int);
void pop();
int xf,yf;
void fill4nonrec(int,int,int,int);
int main()
{
 int gd=DETECT,gm,xc,yc,rx,ry,r,n,choice,ch,newcolor;
 int i,ax[200],ay[200];
 printf("\nEnter the fill color ");
 scanf("%d",&newcolor);
 printf("\nEnter the no of sides ");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
     printf("\nEnter the %d co=ordinates ",i+1);
     scanf("%d%d",&ax[i],&ay[i]);
    }
    printf("\nEnter the inner point ");
    scanf("%d%d",&xf,&yf);
    initgraph(&gd,&gm,"");
    for(i=0;i<n;i++)
     line(ax[i],ay[i],ax[(i+1)%n],ay[(i+1)%n]);
fill4nonrec(xf,yf,newcolor,15);
getch();
return 0;
}

void fill4nonrec(int x,int y,int new1,int bdry)
{
 if(getpixel(x,y)==bdry)
 return;
 push(x,y);
 putpixel(x,y,new1);
 while(head!=NULL)
 {
  pop();
  x=p->x;
  y=p->y;
  if((getpixel(x+1,y)!=bdry)&&(getpixel(x+1,y)!=new1))
  {
   putpixel(x+1,y,new1);
   push(x+1,y);
  }
  if((getpixel(x-1,y)!=bdry)&&(getpixel(x-1,y)!=new1))
  {
   putpixel(x-1,y,new1);
   push(x-1,y);
  }
  if((getpixel(x,y+1)!=bdry)&&(getpixel(x,y+1)!=new1))
  {
   putpixel(x,y+1,new1);
   push(x,y+1);
  }
  if((getpixel(x,y-1)!=bdry)&&(getpixel(x,y-1)!=new1))
  {
   putpixel(x,y-1,new1);
   push(x,y-1);
  }
 }
}
void push(int x1,int y1)
{
 temp=(t1 *)malloc(sizeof(t1));
 temp->x=x1;
 temp->y=y1;
 if(head==NULL)
 {
  head=temp;
  temp->next=NULL;
 }
 else
 {
  temp->next=head;
  head=temp;
 }
}
void pop()
{
 p=head;
 head=head->next;
}

No comments:

Post a Comment