用c++写一个海岛问题
时间: 2024-05-16 11:12:34 浏览: 8
以下是一个简单的用 C 语言实现的海岛问题:
```
#include <stdio.h>
int main() {
int islands[10][10]; // 定义10x10的二维数组存储海岛信息
int row, col; // 定义行和列
int count = 0; // 计数器,计算岛屿数量
// 输入海岛信息
printf("请输入10x10的海岛信息(0表示海洋,1表示陆地):\n");
for (row = 0; row < 10; row++) {
for (col = 0; col < 10; col++) {
scanf("%d", &islands[row][col]);
}
}
// 遍历海岛信息,计算岛屿数量
for (row = 0; row < 10; row++) {
for (col = 0; col < 10; col++) {
if (islands[row][col] == 1) { // 如果当前位置为陆地
count++; // 岛屿数量加1
islands[row][col] = 0; // 将当前位置标记为已经访问过
// 开始搜索相邻的陆地位置
if (row > 0 && islands[row-1][col] == 1) { // 上
islands[row-1][col] = 0;
}
if (col > 0 && islands[row][col-1] == 1) { // 左
islands[row][col-1] = 0;
}
if (row < 9 && islands[row+1][col] == 1) { // 下
islands[row+1][col] = 0;
}
if (col < 9 && islands[row][col+1] == 1) { // 右
islands[row][col+1] = 0;
}
}
}
}
// 输出岛屿数量
printf("岛屿数量为:%d\n", count);
return 0;
}
```
上面的代码中,我们使用一个二维数组 `islands` 存储海岛信息,输入海岛信息后,我们遍历该二维数组,如果当前位置为陆地,则将计数器 `count` 加1,并且将相邻的陆地位置标记为已经访问过。最后输出计数器的值,即为岛屿数量。