洛谷P1141 01迷宫

来源:互联网 发布:迈网络摄像头默认ip 编辑:程序博客网 时间:2024/05/21 09:08
#include <cstdio>using namespace std;struct node{    int x,y,s;}a[1000001];char map[1001][1001]; //map是地图int n,m,startx,starty,num,book[1001][1001],mark[1001][1001],ans[1000001]; //book用来标记一个点走过没有,ans用来储存一种颜色块的联通块数量,mark用来标记每一块的颜色int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; //方向变量int bfs(int color) //color是这一部分的联通块的颜色{    int head=1,tail=2,tx,ty,k,sum=1; //sum是联通块数量    mark[startx][starty]=color; //标记    book[startx][starty]=1; //标记    a[head].x=startx;    a[head].y=starty;    a[head].s=0;    while(head<tail)//模拟队列     {        for(k=0;k<=3;k++)        {            tx=a[head].x+next[k][0];//重点             ty=a[head].y+next[k][1];            if(tx<1 || tx>n || ty<1 || ty>n) //判断是否越界                continue;            if(map[tx][ty]!=map[a[head].x][a[head].y] && book[tx][ty]==0) //如果联通并且没有被算进联通块里过            {                book[tx][ty]=1;                mark[tx][ty]=color; //标记现在他是“color”联通块群里的了                sum++;                a[tail].x=tx;                a[tail].y=ty;                a[tail].s=a[head].s+1;                tail++;            }        }        head++;    }    return sum; //返回联通块的数量}int main(){    num=1;    int i,j;    scanf("%d %d\n",&n,&m);    for(i=1;i<=n;i++)    {        gets(map[i]+1);    }    for(i=1;i<=m;i++)    {        scanf("%d %d",&startx,&starty);        if(mark[startx][starty]!=0) //如果这个点有所属的联通块群        {            printf("%d\n",ans[mark[startx][starty]]); //直接输出以前储存的答案        }        else //如果没有        {            ans[num]=bfs(num); //求一次联通块,并且保存答案            printf("%d\n",ans[num]); //输出答案                        num++;        }    }    return 0;}/*总结:本题主要思路是判断是否被标记,进队,取出队头,进行四位搜索,判越界然后更新,进队。。。。。 本题用了gets函数进行读取,然后方向x是next[k][0],y是next[k][1], 还有 队头队尾表示方法。 */