栈的应用-区域填充
目的
1.掌握栈的定义及实现;
2.掌握利用栈实现区域填充。
要求
(1)通过二维数组输入一幅边界图像;
(2)建立图像坐标数据结构;
(3)建立图像像素点栈;
(4)从边界中心出发,通过进栈和出栈操作实现边界内的区域填充。
代码实现
主类
包含的文件
#include"stdio.h"
#include"stdlib.h"
#include"windows.h"
#include "Sqstack.h"
常量赋值,方便改变边界大小以及栈的长度
#define X 10 //控制边界大小
#define N 200 //控制栈长度
#define Y 10
定义结构体(二维数组)用于表示位置
typedef struct
{
char presentation[X][Y]; //数组表示位置
}position;
函数声明
void show(position *p); //函数声明
void Full(position *p);
主函数
void main()
{
int s=0;
int i=0,a=0,b=0;
position aa;
position *p;
p=&aa;
for(a=0;a<X;a++)
{
for(b=0;b<Y;b++)
{
if(b==0||b==Y-1||a==0||a==X-1)
{
p->presentation[a][b]='1';}
else
{
p->presentation[a][b]='\0';}
}
}
show(p);
printf("是否进行填充:\n是输入:1\n否输入:2\n");
scanf("%d",&i);
switch(i)
{
case 1:
Full(p);
case 2:
break;
}
}
展示函数
void show(position *p)
{
int show_x=0,show_y=0;
Sleep(5); //休眠
system("cls"); //清屏
while(show_y<=Y-1)
{
while(show_x<=X-1)
{
printf("%2c",p->presentation[show_x][show_y]);
show_x++;
}
show_x=0;
show_y++;
printf("\n");
}
}
堆栈填充函数
void Full(position *p)
{
int current_y,current_x;
Sqstack s(N); //栈初始化
int m=(X-2)*(Y-2); //填充次数
current_x=X/2-1;
current_y=0;
// s.Push(current_x);
// s.Push(current_y); 测试用
// current_y=s.Pop();
// current_x=s.Pop();
// p->presentation[current_x][current_y]='0';
// show(p);
int x1,x2,x3,x4,y1,y2,y3,y4; //定义周围三个点的位置
while(m!=0)
{
x1=current_x+1;
y1=current_y;
x2=current_x-1;
y2=current_y;
x3=current_x; //周围三个点的位置
y3=current_y-1;
x4=current_x;
y4=current_y+1;
if(x1>0&&x1<X-1&&y1>0&&y1<Y-1) //在边界内
{
if(p->presentation[x1][y1]!='0') //没有填充
{
s.Push(x1);//位置信息前后入栈
s.Push(y1);
}
}
if(x2>0&&x2<X-1&&y2>0&&y2<Y-1)
{
if(p->presentation[x2][y2]!='0')
{
s.Push(x2);
s.Push(y2);
}
}
if(x3>0&&x3<X-1&&y3>0&&y3<Y-1)
{
if(p->presentation[x3][y3]!='0')
{
s.Push(x3);
s.Push(y3);
}
}
if(x4>0&&x4<(X-1)&&y4>0&&y4<(Y-1))
{
if(p->presentation[x4][y4]!='0')
{
s.Push(x4);//下面的点在栈顶
s.Push(y4);
}
}
current_y=s.Pop();
current_x=s.Pop(); //栈顶元素出栈
if(p->presentation[current_x][current_y]!='0'&&p->presentation[current_x][current_y]!='1')//没有填充且不是边界
{
p->presentation[current_x][current_y]='0';
show(p);
m--;//循环条件
}
}
printf("\n填充完成!\n");
}
栈类
#include "Sqstack.h"
#include"stdio.h"
#include"stdlib.h"
#include"windows.h"
//
// Construction/Destruction
//
Sqstack::Sqstack(int m)
{
stacksize=m;
base=new int[m];
top=-1;
}
Sqstack::~Sqstack()
{
delete[] base;
top=-1;
stacksize=0;
}
void Sqstack::Push(int e)
{
if (top==stacksize-1)
{
return;
}
top++;
base[top]=e;
}
bool Sqstack::StackEmpty()
{
if(top==-1)
return true;
else
return false;
}
int Sqstack::Pop()
{
int e;
if(top==-1)
{
return 0;
}
e=base[top--];
return e;
}
int Sqstack::GetTop()
{
int e;
e=base[top];
return e;
}
运行结果
思路
我用的是VC++6.0,因为只是区域填充,用不着MFC,主要还是把出入栈的算法搞清楚,我是先右边的点再左边的点,然后最下面的点,因为我想让它从上往下开始。用到的是二维数组,所以,出入栈要两个一起,一定要注意顺序。