ZOJ 1047 Image Perimeters

来源:互联网 发布:海牛大数据 编辑:程序博客网 时间:2024/06/06 10:50

大意:给出一张有“.”和“X”组成的图,给出点击位置s,t。求由s,t以及附近不包含”.”的由”X”组成的联通图的周长。
做法:很容易发现,当一个“X”上下左右四个位置没有“X”的时候就会有边,因此,我们BFS搜索由S,T出发能到达的所有是“X”的点,每个“X”的上下左右四个位置有几个“.”就有几条边。搜索完即可。

#include <iostream>#include <cstring>#include <cstdio>#include <queue>using namespace std;struct point{    int x,y;};int r,c,s,t;int map1[22][22],flag[22][22];int dir[8][2]={{1,0},{-1,0},{0,1},{0,-1},{1,1},{-1,1},{-1,-1},{1,-1}};int BFS(){    int ans = 0;    queue<point> q;    while(!q.empty()) q.pop();    point a;    a.x = s;    a.y = t;    q.push(a);    flag[s][t] = 1;    while(!q.empty())    {        a = q.front();        q.pop();        for(int i = 0 ; i < 8 ; i++)        {            point b;            b.x = a.x + dir[i][0];            b.y = a.y + dir[i][1];            if(!flag[b.x][b.y])            {                if(map1[b.x][b.y])                {                    flag[b.x][b.y] = 1;                    q.push(b);                }                else if(i < 4)//前四个方向数组代表上下左右。                    ans++;            }        }    }    return ans;}int main(){    while(~scanf("%d%d%d%d",&r,&c,&s,&t))    {        if(r+c+s+t == 0) return 0;        getchar();        memset(map1,0,sizeof(map1));        memset(flag,0,sizeof(flag));        for(int i = 0 ; i < r ; i ++)        {            for (int j = 0 ; j < c ; j++)            {                char c;                scanf("%c",&c);                if(c=='X') map1[i+1][j+1] = 1;            }            getchar();        }        int ans = BFS();        printf("%d\n",ans);    }    return 0;}
0 0
原创粉丝点击