C语言实现区域填充算法:基于栈的方案

实现一个基于栈的区域填充算法,需要先定义一个栈结构体,并实现入栈、出栈、判断栈是否为空等基本操作。

然后,我们可以定义一个二维数组来表示需要填充的区域,以及一个点结构体来表示每个点的坐标。

接着,我们从某一个起始点开始,将其入栈,并将其标记为已访问。然后,我们进入一个循环,每次取出栈顶元素,访问其上下左右四个相邻点,如果相邻点未被访问且颜色相同,则将其入栈,并将其标记为已访问。直到栈为空,算法结束。

下面是一份示例代码,仅供参考:

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

typedef struct {
    int x;
    int y;
} Point;

typedef struct {
    Point items[MAX_SIZE];
    int top;
} Stack;

void initStack(Stack *stack) {
    stack->top = -1;
}

int isEmpty(Stack *stack) {
    return stack->top == -1;
}

void push(Stack *stack, Point p) {
    stack->items[++stack->top] = p;
}

Point pop(Stack *stack) {
    return stack->items[stack->top--];
}

Point peek(Stack *stack) {
    return stack->items[stack->top];
}

int isVisited(int visited[][10], Point p) {
    return visited[p.x][p.y];
}

void setVisited(int visited[][10], Point p) {
    visited[p.x][p.y] = 1;
}

int isSameColor(int color[][10], Point p, int c) {
    return color[p.x][p.y] == c;
}

void fill(int color[][10], int visited[][10], Point start, int c) {
    Stack stack;
    initStack(&stack);
    push(&stack, start);
    setVisited(visited, start);
    while (!isEmpty(&stack)) {
        Point p = pop(&stack);
        color[p.x][p.y] = c;
        Point up = {p.x - 1, p.y};
        Point down = {p.x + 1, p.y};
        Point left = {p.x, p.y - 1};
        Point right = {p.x, p.y + 1};
        if (p.x > 0 && !isVisited(visited, up) && isSameColor(color, up, c)) {
            push(&stack, up);
            setVisited(visited, up);
        }
        if (p.x < 9 && !isVisited(visited, down) && isSameColor(color, down, c)) {
            push(&stack, down);
            setVisited(visited, down);
        }
        if (p.y > 0 && !isVisited(visited, left) && isSameColor(color, left, c)) {
            push(&stack, left);
            setVisited(visited, left);
        }
        if (p.y < 9 && !isVisited(visited, right) && isSameColor(color, right, c)) {
            push(&stack, right);
            setVisited(visited, right);
        }
    }
}

void printColor(int color[][10]) {
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            printf("%d ", color[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int color[10][10] = {
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 1, 1, 1, 1, 1, 1},
        {1, 0, 0, 0, 1, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 1, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 1, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 1, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 1, 1, 1, 1, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
    };
    int visited[10][10] = {0};
    Point start = {1, 1};
    fill(color, visited, start, 2);
    printColor(color);
    return 0;
}
C语言实现区域填充算法:基于栈的方案

原文地址: https://www.cveoy.top/t/topic/lLFg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录