卫星照片(搜索)

题目描述
牧羊人达瓦正在研究他们牧场的卫星照片.照片为一个R(1<=R<=75)行C(1<=C<=75)列的字符矩阵表示。如下图:

…#####…##…
…#####…##…

#…###…#.
#…#####…
图上的一块相连通的#表示一群绵羊或一个帐篷,两个子#连通的意思是说左右或上下相连。而下面的两块则是分开的:

.#…
…#.

达瓦现在根据卫星照片上的的这些#块的形状来判断哪些是羊群,哪些是帐篷。如果矩形内只有#,则是帐篷,其它的则认为都是羊群。在第一个图中,有三个帐篷(2∗1,2∗5,and 1∗1)和2群羊。根据输入的数据,统计出帐篷数和羊群数,数据中羊群不会包围另一个羊群或帐篷。

输入
第一行,两个整数:R和C.和2…R+1行:第i+1行表示照片的第i行情况,由C字符组成。

输出
第一行: 帐篷数。
第二行: 羊群数。

样例输入
5 8
#####…#
#####.##
…#.
.###…#
.###…##

样例输出
2
2

思路
dfs搜索,通过四个角判断矩形大小,从而判断是否是羊群

代码实现

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef long long ll;
const int N=105;
bool m[N][N];
int r,c;
int mah,mih,mal,mil,ans;
int ansz,ansy;
int w[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
bool judge(int x,int y)
{
    if(x>0 || x<=r || y>0 || y<=c) return true;
    return false;
}
void dfs(int x,int y)
{
    m[x][y]=false;
    mah=max(mah,x),mih=min(mih,x);
    mal=max(mal,y),mil=min(mil,y);
    ans++;
    for(int i=0;i<4;i++)
    {
        int ax=x+w[i][0],ay=y+w[i][1];
        if(m[ax][ay] && judge(ax,ay)) dfs(ax,ay);
    }
}
int main()
{
    cin>>r>>c;
    for(int i=1;i<=r;i++)
        for(int j=1;j<=c;j++)
        {
            char tmp;
            cin>>tmp;
            if(tmp=='#') m[i][j]=true;
        }
    for(int i=1;i<=r;i++)
    {
        for(int j=1;j<=c;j++)
        {
            if(m[i][j])
            {
                ans=0;
                mah=0,mal=0,mih=1e9,mil=1e9;
                dfs(i,j);
                if(ans==(mah-mih+1)*(mal-mil+1)) ansz++;
                else ansy++;
            }
        }
    }
    cout<<ansz<<endl<<ansy<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43935894/article/details/88342843
今日推荐