标题: | 宝岛探险 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
标签: | 搜索 深度优先搜索 广度优先搜索 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
详情: | 小哼通过秘密方法得到一张不完整的钓鱼岛航拍地图。钓鱼岛由一个主岛和一些附属岛屿组成,小哼决定去钓鱼岛探险。下面这个10*10的二维矩阵就是钓鱼岛的航拍地图。图中数字表示海拔,0表示海洋,1~9都表示陆地。小哼的飞机将会降落在(6,8)处,现在需要计算出小哼降落所在岛的面积(即有多少个格子)。注意此处我们把与小哼降落点上下左右相链接的陆地均视为同一岛屿。
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
输入格式: | | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
输出格式: | | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
限制: | n<=100 m<=100 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
样例: |
|
/* BFS */
#include <stdio.h>
#define maxn 105
int ar[maxn][maxn], flag[maxn][maxn];
int next[4][2] = {
0, 1,
1, 0,
0, -1,
-1, 0,
};
struct node{
int x;
int y;
}que[10050];
int main()
{
int i, j, k, tx, ty, n, m, p, q, head = 1, tail = 1, step = 1;
scanf("%d %d %d %d", &n, &m, &p, &q);
for(i = 1; i <= n; i++)
for(j = 1; j <= m; j++)
scanf("%d", &ar[i][j]);
flag[p][q] = 1;
que[tail].x = p;
que[tail].y = q;
tail++;
while(head < tail){
for(k = 0; k < 4; k++)
{
tx = que[head].x + next[k][0];
ty = que[head].y + next[k][1];
if(tx > n || ty > m || tx < 1 || ty < 1)
continue;
if(ar[tx][ty] != 0 && flag[tx][ty] == 0)
{
que[tail].x = tx;
que[tail].y = ty;
flag[tx][ty] = 1;
tail++;
step++;
}
}
head++;
}
printf("%d", step);
return 0;
}
/* DFS */
#include <stdio.h>
#define maxn 105
int ar[maxn][maxn], flag[maxn][maxn];
int n, m, p, q, step=1;
int next[4][2] = {
0, 1,
1, 0,
0, -1,
-1, 0,
};
void dfs(int x, int y)
{
int k, tx, ty;
for(k = 0; k < 4; k++)
{
tx = x + next[k][0];
ty = y + next[k][1];
if(tx > n || ty > m || tx < 1 || ty < 1)
continue;
if(ar[tx][ty] != 0 && flag[tx][ty] == 0)
{
flag[tx][ty] = 1;
step++;
dfs(tx,ty);
}
}
return;
}
int main()
{
int i, j;
scanf("%d %d %d %d", &n, &m, &p, &q);
for(i = 1; i <= n; i++)
for(j = 1; j <= m; j++)
scanf("%d", &ar[i][j]);
flag[p][q] = 1;
dfs(p,q);
printf("%d", step);
return 0;
}
在原本dfs的基础上,添加少量代码即可实现简单的FLOODFILL漫水填充法:
#include <stdio.h>
#define maxn 105
int ar[maxn][maxn], flag[maxn][maxn];
int n, m, p, q, step=1;
int next[4][2] = {
0, 1,
1, 0,
0, -1,
-1, 0,
};
void dfs(int x, int y, int color)
{
int k, tx, ty;
ar[x][y] = color; /**/
for(k = 0; k < 4; k++)
{
tx = x + next[k][0];
ty = y + next[k][1];
if(tx > n || ty > m || tx < 1 || ty < 1)
continue;
if(ar[tx][ty] != 0 && flag[tx][ty] == 0)
{
flag[tx][ty] = 1;
step++;
dfs(tx,ty,color);
}
}
return;
}
int main()
{
int i, j;
scanf("%d %d %d %d", &n, &m, &p, &q);
for(i = 1; i <= n; i++)
for(j = 1; j <= m; j++)
scanf("%d", &ar[i][j]);
flag[p][q] = 1;
dfs(p, q, -1); /**/
for(i = 1; i <= n; i++){
for(j = 1; j <= m; j++){
printf("%3d", ar[i][j]);
}
printf("\n");
}
return 0;
}