1.计算岛屿面积
1.1 BFS
#include <stdio.h>
int a[10][10] = {
{1,2,1,0,0,0,0,0,2,3},
{3,0,2,0,1,2,1,0,1,2},
{4,0,1,0,1,2,3,2,0,1},
{3,2,0,0,0,1,2,4,0,1},
{0,0,0,0,0,0,1,5,3,0},
{0,1,2,1,0,1,5,4,3,0},
{0,1,2,3,1,3,6,2,1,0},
{0,0,3,4,8,9,7,5,0,0},
{0,0,0,3,7,8,6,0,1,2},
{0,0,0,0,0,0,0,0,1,0}
};
/*
0表示海洋,1-9表示陆地的海拔,降落在(6,8)处,计算出该岛的面积(有多少个格子)。
即从(6,8)处进行广度优先搜索, sum ++
*/
struct note{
int x;
int y;
};
int main(){
struct note que[101];
int head,tail;
int book[10][10]={0};
int startx = 6, starty = 8;
int sum=0;
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};//右下左上
//初始化队列
head = 1;
tail = 1;
que[tail].x = startx;
que[tail].y = starty;
book[startx][starty] = 1;
tail++;
sum++;
while(head < tail){
for(k = 0; k <= 3; k++){
tx = que[head].x + next[k][0];
ty = que[head].y + next[k][1];
if(tx < 0 || tx > 9 || ty < 0 || ty > 9){
continue;
}
if(a[tx][ty] > 0 && book[tx][ty] == 0){
book[tx][ty] = 1;
sum++;
que[tail].x = tx;
que[tail].y = ty;
tail++;
}
}
head++;
}
printf("该岛屿面积为%d.\n",sum);
getchar();
return 0;
}
1.2 DFS
#include <stdio.h>
int a[10][10] = {
{1,2,1,0,0,0,0,0,2,3},
{3,0,2,0,1,2,1,0,1,2},
{4,0,1,0,1,2,3,2,0,1},
{3,2,0,0,0,1,2,4,0,1},
{0,0,0,0,0,0,1,5,3,0},
{0,1,2,1,0,1,5,4,3,0},
{0,1,2,3,1,3,6,2,1,0},
{0,0,3,4,8,9,7,5,0,0},
{0,0,0,3,7,8,6,0,1,2},
{0,0,0,0,0,0,0,0,1,0}
};
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};//右下左上
/*
0表示海洋,1-9表示陆地的海拔,降落在(6,8)处,计算出该岛的面积(有多少个格子)。
即从(6,8)处进行深度优先搜索, sum ++
*/
int book[10][10] = {0};
int sum;
void dfs(int x,int y){
int k,tx,ty;
for(k=0;k<=3;k++){
tx = x + next[k][0];
ty = y + next[k][1];
if(tx < 0 || tx > 9 || ty < 0 || ty > 9){
continue;
}
if(a[tx][ty] > 0 && book[tx][ty] == 0){
sum ++;
book[tx][ty] = 1;
dfs(tx,ty);
}
}
return ;
}
int main(){
int i,j,startx = 6,start = 8;
book[startx][starty] = 1;
sum = 1;
dfs(startx.starty);
printf("%d\n",sum);
getchar();
return 0;
}
2.一共有几个岛(独立子图个数)
着色法
#include <stdio.h>
int a[10][10] = {
{1,2,1,0,0,0,0,0,2,3},
{3,0,2,0,1,2,1,0,1,2},
{4,0,1,0,1,2,3,2,0,1},
{3,2,0,0,0,1,2,4,0,1},
{0,0,0,0,0,0,1,5,3,0},
{0,1,2,1,0,1,5,4,3,0},
{0,1,2,3,1,3,6,2,1,0},
{0,0,3,4,8,9,7,5,0,0},
{0,0,0,3,7,8,6,0,1,2},
{0,0,0,0,0,0,0,0,1,0}
};
/*
0表示海洋,1-9表示陆地的海拔。求有几个岛屿。
*/
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};//右下左上
int book[10][10] = {0};
int sum;
void dfs(int x,int y, int color){
int k, tx, ty;
a[x][y] = color;
for(k = 0; k <= 3; k++){
tx = x + next[k][0];
ty = y + next[k][1];
if(tx < 0 || tx > 9 || ty < 0 || ty > 9){
continue;
}
if(a[tx][ty] > 0 && book[tx][ty] == 0){
book[tx][ty] = 1;
sum++;
dfs(tx,ty,color);
}
}
return ;
}
int main(){
int i,j,num = 0;
for(i=0; i<=9;i++){
for(j=0;j<=9;j++){
if(a[i][j] > 0){
num--;
book[i][j] = 1;
dfs(i,j,num);
}
}
}
//输出着色后的地图
for(i=0; i<=9;i++){
for(j=0;j<=9;j++){
printf("%3d",a[i][j]);
}
printf("\n");
}
printf("共有%d个小岛。",-num);
getchar();
return 0;
}