用C语言写一个区域填充算法,用进栈出栈知识,有注释,适用于Visual C++6.0
本算法使用进栈出栈的思想,实现了一个简单的区域填充功能。具体实现过程如下:
- 定义一个栈结构,用于存储待填充的像素点的坐标。
- 定义一个函数,用于将一个像素点的坐标压入栈中。
- 定义一个函数,用于从栈中弹出一个像素点的坐标。
- 定义一个函数,用于判断一个像素点是否需要填充。如果需要填充,则将该点压入栈中。
- 定义一个函数,用于实现区域填充功能。该函数使用一个循环,不断从栈中取出像素点,并判断其周围的像素点是否需要填充。如果需要填充,则将该点压入栈中。
- 定义一个主函数,调用上述函数实现区域填充功能。
具体代码实现如下:
#include <stdio.h> #include <stdlib.h>
#define WIDTH 20 // 图像宽度 #define HEIGHT 15 // 图像高度
struct point // 定义像素点结构 { int x; int y; };
struct stack // 定义栈结构 { struct point data[WIDTH*HEIGHT]; int top; };
void push(struct stack *s, struct point p) // 入栈操作 { s->data[++s->top] = p; }
struct point pop(struct stack *s) // 出栈操作 { return s->data[s->top--]; }
int needFill(int image[HEIGHT][WIDTH], int x, int y, int color) // 判断是否需要填充 { if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) // 判断坐标是否越界 return 0; if (image[y][x] != color) // 判断像素点颜色是否与填充颜色相同 return 0; return 1; }
void fill(int image[HEIGHT][WIDTH], int x, int y, int color) // 区域填充函数 { struct stack s; s.top = -1; struct point p = {x, y}; push(&s, p); // 先将起始点压入栈中 while (s.top != -1) // 栈不为空时,继续填充 { p = pop(&s); if (needFill(image, p.x, p.y, color)) // 判断是否需要填充 { image[p.y][p.x] = color; // 填充像素点 push(&s, (struct point){p.x-1, p.y}); // 将周围的像素点压入栈中 push(&s, (struct point){p.x+1, p.y}); push(&s, (struct point){p.x, p.y-1}); push(&s, (struct point){p.x, p.y+1}); } } }
int main() { int image[HEIGHT][WIDTH] = { // 定义图像 {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} };
fill(image, 5, 5, 1); // 以像素点(5,5)为起始点,将图像填充为颜色1
// 输出填充后的图像
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
printf("%d ", image[i][j]);
}
printf("\n");
}
return 0;
}
原文地址: http://www.cveoy.top/t/topic/z7C 著作权归作者所有。请勿转载和采集!