DFS【模板】 宝岛探险

标题:宝岛探险
标签:搜索深度优先搜索广度优先搜索
详情:
小哼通过秘密方法得到一张不完整的钓鱼岛航拍地图。钓鱼岛由一个主岛和一些附属岛屿组成,小哼决定去钓鱼岛探险。下面这个10*10的二维矩阵就是钓鱼岛的航拍地图。图中数字表示海拔,0表示海洋,1~9都表示陆地。小哼的飞机将会降落在(6,8)处,现在需要计算出小哼降落所在岛的面积(即有多少个格子)。注意此处我们把与小哼降落点上下左右相链接的陆地均视为同一岛屿。
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
0
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
输入格式:
一行4个整数,前两个整数表示n行m列,后两个整数表示降落的坐标x行y列
输出格式:
一个整数表示岛屿的面积
限制:n<=100
m<=100
样例:

输入

10 10 6 8
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 0
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

输出

38

题解:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
using namespace std;
int ans=1;
int a[110][110];
int n,m;
int dir[4][2]={0,1,-1,0,0,-1,1,0};
int vis[110][110];
void dfs(int x,int y){
    for(int i=0;i<4;i++){
        int tx=x+dir[i][0];
        int ty=y+dir[i][1];
        if(tx<=0||tx>n||ty<=0||ty>m){
            continue;
        }
        if(!vis[tx][ty]&&a[tx][ty]>0){
            vis[tx][ty]=1;
            ans++;
            a[tx][ty]=-1;
            dfs(tx,ty);
        }
    }
    return;
}
int main()
{
    int sx,sy;
    scanf("%d %d %d %d",&n,&m,&sx,&sy);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            scanf("%d",&a[i][j]);
        }
    }
    memset(vis,0,sizeof vis);
    vis[sx][sy]=1;
    dfs(sx,sy);
    printf("%d
",ans);
    return 0;
}


原文地址:https://www.cnblogs.com/kzbin/p/9205240.html