• (bfs入门)宝岛探险


    小哼通过秘密方法得到一张不完整的钓鱼岛航拍地图。钓鱼岛由一个主岛和一些附属岛屿组成,小哼决定去钓鱼岛探险。

    下面这个n*m的二维矩阵就是钓鱼岛的航拍地图。图中数字表示海拔,0表示海洋,1~9都表示陆地。小哼的飞机将会降落在(x,y)处,现在需要计算出小哼降落所在岛的面积(即有多少个格子)。注意此处我们把与小哼降落点上下左右相链接的陆地均视为同一岛屿。

    输入样例;

    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 <string.h>
    #include <iostream>
    #include <algorithm>
    #include <sstream>
    #include <math.h>
    #include <queue>
    using namespace std;
    const int inf=0x7fffffff;
    const long long mod=1e9+7;
    const double PI=acos(-1);
    
    int n,m;
    int ans;
    bool vis[105][105];
    int a[105][105];
    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//四个方向
    bool in(int x,int y){
        return x>=0&&x<n&&y>=0&&y<m;
    }
    struct node{
        int x,y,d;
        node(int xx,int yy,int dd){
            x=xx;
            y=yy;
            d=dd;
        }
    };
    int bfs(int sx,int sy){
        queue<node> q;
        q.push(node(sx,sy,0));
        vis[sx][sy]=1;
        while(!q.empty()){                                     //遍历队列 每次将遍历的边界入队 
            node now = q.front();
            q.pop();
            for(int i=0;i<4;i++){                               //依此遍历每个节点的四个方向 
                int tx=now.x+next[i][0];
                int ty=now.y+next[i][1];
                if(in(tx,ty)&&a[tx][ty]>0&&!vis[tx][ty]){       //未访问过 并且在地图陆地里面  
                    vis[tx][ty]=1;
                    q.push(node(tx,ty,now.d+1));
                    ans++;                                      //每遍历一个节点面积+1 
                }
            }
        }
        return ans;
    }
    int main()
    {
        int x,y;
        cin>>n>>m>>x>>y;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>a[i][j];
            }
        }
        ans=1;
        cout<<bfs(x,y);
        return 0;
    }
  • 相关阅读:
    shell tr命令的使用
    linux find prune排除某目录或文件
    在vue中使用axios发送post请求,参数方式
    webpack官网demo起步中遇到的问题
    css中盒子模型与box-sizing属性
    jquery获得 url的变量
    17-js观察者模式
    基于Jquery ui 可复用的酒店 web页面选择入住日期插件
    webkit浏览器下改变滚动条样式
    用户登录时,禁止chrome提示用户保存密码
  • 原文地址:https://www.cnblogs.com/xusi/p/12573000.html
Copyright © 2020-2023  润新知