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

#define MAX_SIZE 182

int screen[MAX_SIZE][MAX_SIZE]; int distance[MAX_SIZE][MAX_SIZE]; int n, m;

int min(int a, int b) { return (a < b) ? a : b; }

// 计算每个像素点到最近的白色像素点的最短距离 void bfs() { // 初始化距离矩阵 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { distance[i][j] = -1; } }

// 使用队列来进行广度优先搜索
int queue[MAX_SIZE * MAX_SIZE][2];
int front = 0;
int rear = 0;

// 将白色像素点入队,距离设为0
for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        if (screen[i][j] == 1) {
            queue[rear][0] = i;
            queue[rear][1] = j;
            distance[i][j] = 0;
            rear++;
        }
    }
}

// 使用BFS搜索
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

while (front < rear) {
    int x = queue[front][0];
    int y = queue[front][1];
    front++;

    for (int i = 0; i < 4; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];

        // 判断是否在屏幕范围内,是否为黑色像素,以及是否更新距离
        if (nx >= 0 && nx < n && ny >= 0 && ny < m && screen[nx][ny] == 0 && distance[nx][ny] == -1) {
            queue[rear][0] = nx;
            queue[rear][1] = ny;
            distance[nx][ny] = distance[x][y] + 1;
            rear++;
        }
    }
}

}

int main() { // 读取输入 scanf("%d %d", &n, &m);

for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        scanf("%d", &screen[i][j]);
    }
}

// 进行广度优先搜索
bfs();

// 输出结果
for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        printf("%d ", distance[i][j]);
    }
    printf("\n");
}

return 0;

}

C语言代码:计算每个像素点到最近的白色像素点的最短距离

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

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