zoukankan      html  css  js  c++  java
  • 宝岛探险,DFS&BFS

    • 问题描述:

    小哼通过秘密方法得到一张不完整的钓鱼岛航拍地图。钓鱼岛由一个主岛和一些附属岛屿组成,小哼决定去钓鱼岛探险。下面这个10*10的二维矩阵就是钓鱼岛的航拍地图。图中数字表示海拔,0表示海洋,1~9都表示陆地。小哼的飞机将会降落在(6,8)处,现在需要计算出小哼降落所在岛的面积(即有多少个格子)。注意此处我们把与小哼降落点上下左右相链接的陆地均视为同一岛屿。

    样例输入:

    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<cstdio>
    #include<iostream>
    #define INF 10000000
    using namespace std;
    int a[20][20];
    int b[20][20];
    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//四个方向
    int tx,ty,n,m,sum=0;
    
    void dfs(int x,int y)
    {
        for(int i=0;i<4;i++)
        {
            tx=x+next[i][0];
            ty=y+next[i][1];
            if(tx>n||ty>m||tx<1||ty<1)//判断越界
                continue;
            if(b[tx][ty]==0&&a[tx][ty]>0)//未被标记并且是陆地
            {
                sum++;
                b[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]);
        b[sx][sy]=1;
        sum=1;
        dfs(sx,sy);
        printf("%d
    ",sum);
        return 0;
    }
    • 广搜代码:

    #include<cstdio>
    #include<iostream>
    #define INF 10000000
    using namespace std;
    int a[20][20];
    int b[20][20];
    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//四个方向
    int tx,ty,n,m,sum=0;
    struct node
    {
        int x,y;
    }que[405];
    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]);
        int head=1,tail=1;
        que[tail].x=sx;
        que[tail].y=sy;
        tail++;
        b[sx][sy]=1;
        sum=1;
        while(head<tail)
        {
            for(int i=0;i<4;i++){
                tx=que[head].x+next[i][0];
                ty=que[head].y+next[i][1];
                if(tx<1||ty<1||tx>n||ty>m)
                    continue;
                if(b[tx][ty]==0&&a[tx][ty]>0)
                {
                    sum++;
                    b[tx][ty]=1;//标记
                    que[tail].x=tx;
                    que[tail].y=ty;
                    tail++;
                }
            }
            head++;
        }
        printf("%d
    ",sum);
        return 0;
    }
  • 相关阅读:
    爱普生L4168打印出来是白纸,复印OK,打印机测试也OK 解决方案
    json序列化对象
    "割裂"的西安
    资金投资心得
    【练内功,促成长】算法学习(3) 二分查找
    在ReactNative中实现Portal
    node创建GIT分支,并修改代码提交
    关于"三分钟热度"问题的思考
    参考vue-cli实现自己的命令行工具(demo)
    【练内功,促成长】算法学习(2) 排序算法
  • 原文地址:https://www.cnblogs.com/boboyuzz/p/10426500.html
Copyright © 2011-2022 走看看