区域填充算法是一种基本的计算机图形学算法,用于填充封闭区域。本文提供一个基于C语言的区域填充算法的示例代码。

算法思路:

  1. 选取一个起始点(x,y)。

  2. 将该点填充为目标颜色,同时将该点入队。

  3. 从队列中取出一个点(x,y)。

  4. 检查该点的四周4个相邻点是否为边界或已经填充过。

  5. 如果4个相邻点都不是边界或已经填充过,则将它们填充为目标颜色,并将它们入队。

  6. 重复步骤3-5直到队列为空。

代码实现:

#include <stdio.h>

#define WIDTH 10
#define HEIGHT 10

void fill(int x, int y, int target_color, int replace_color, int image[WIDTH][HEIGHT])
{
    if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT) {
        return;
    }
    if (image[x][y] != target_color || image[x][y] == replace_color) {
        return;
    }
    image[x][y] = replace_color;
    fill(x - 1, y, target_color, replace_color, image);
    fill(x + 1, y, target_color, replace_color, image);
    fill(x, y - 1, target_color, replace_color, image);
    fill(x, y + 1, target_color, replace_color, image);
}

int main()
{
    int image[WIDTH][HEIGHT] = {
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
    };

    int x = 5;
    int y = 5;
    int target_color = 0;
    int replace_color = 2;

    fill(x, y, target_color, replace_color, image);

    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            printf("%d ", image[j][i]);
        }
        printf("\n");
    }

    return 0;
}

该示例代码中,我们定义了一个10×10的二维数组表示图像。我们选取了坐标为(5,5)的点作为起始点,并将目标颜色设为0,将填充颜色设为2。我们调用fill函数进行填充,该函数会将所有与起始点相连的、颜色为0的点都填充为2。最后我们遍历整个数组,输出填充后的结果。

C语言区域填充算法实现:示例代码与详解