用c语言写一个区域填充算法
区域填充算法是一种用于填充封闭区域的图形算法。其基本思想是从一个起始点开始,向四周扩展,直到填满整个区域。以下是用C语言实现的区域填充算法:
#include <stdio.h>
#include <graphics.h>
// 定义颜色常量
#define WHITE 15
#define BLACK 0
#define RED 4
// 定义点结构体
typedef struct {
int x;
int y;
} Point;
// 定义栈结构体
typedef struct {
Point data[1000];
int top;
} Stack;
// 初始化栈
void init(Stack *s) {
s->top = -1;
}
// 入栈
void push(Stack *s, Point p) {
s->top++;
s->data[s->top] = p;
}
// 出栈
Point pop(Stack *s) {
Point p = s->data[s->top];
s->top--;
return p;
}
// 判断点是否在边界内
int inside(int x, int y, int boundary) {
return x >= boundary && x <= getmaxx() - boundary && y >= boundary && y <= getmaxy() - boundary;
}
// 区域填充函数
void fill(Point p, int fillColor, int boundaryColor) {
Stack s;
init(&s);
push(&s, p);
while (s.top >= 0) {
Point curr = pop(&s);
int x = curr.x;
int y = curr.y;
if (getpixel(x, y) != boundaryColor && getpixel(x, y) != fillColor && inside(x, y, 1)) {
putpixel(x, y, fillColor);
push(&s, (Point){x+1, y});
push(&s, (Point){x-1, y});
push(&s, (Point){x, y+1});
push(&s, (Point){x, y-1});
}
}
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// 画一个矩形作为边界
rectangle(50, 50, 250, 150);
// 点选一个起始点
Point p = {100, 100};
// 填充矩形内部
fill(p, RED, BLACK);
getch();
closegraph();
return 0;
}
在主函数中,我们首先初始化了图形界面,然后画了一个矩形作为边界。接着,我们点选了一个起始点,调用fill函数进行填充。fill函数中,我们使用了一个栈来存储需要填充的点,然后从起始点开始向四周扩展,如果遇到了边界或已经被填充过的点,就不再扩展,否则将该点入栈,并将它的四周的点也入栈,继续扩展。最终,整个区域就被填充了。
原文地址: https://www.cveoy.top/t/topic/xzB 著作权归作者所有。请勿转载和采集!