题目描述:https://blog.csdn.net/qq_44813449/article/details/126212443
https://pycoder.blog.csdn.net/article/details/125175834
思路:先把5周边的像素转成0,然后遍历到0时判断是否属于同一个边界就可以了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int M, N;
int arr[100][100];
void func(int row, int col) {
int row_start = (row - 1) < 0 ? 0 : (row - 1);
int row_end = (row + 1) >= M ? (M - 1) : (row + 1);
int col_start = (col - 1) < 0 ? 0 : (col - 1);
int col_end = (col + 1) >= N ? (N - 1) : (col + 1);
for (int i = row_start; i <= row_end; i++) {
for (int j = col_start; j <= col_end; j++) {
if (arr[i][j] != 5) {
arr[i][j] = 0;
}
}
}
}
int isGap(int row, int col) {
if (row == 0 && col == 0) {
return 1;
} else if (row == 0 && col != 0) {
if (arr[row][col - 1] != 0) {
return 1;
} else {
return 0;
}
} else if (row != 0 && col == 0) {
if (arr[row - 1][col] != 0) {
return 1;
} else {
return 0;
}
} else {
if (arr[row][col - 1] == 0 || arr[row - 1][col] == 0 || arr[row - 1][col - 1] == 0) {
return 0;
} else {
return 1;
}
}
}
int main(void) {
int res = 0;
scanf("%d %d", &M, &N);
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
scanf("%d", &arr[i][j]);
}
}
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] == 5) {
func(i, j);
}
}
}
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", arr[i][j]);
if (arr[i][j] == 0) {
res += isGap(i, j);
}
}
printf("\n");
}
printf("%d\n", res);
return 0;
}