hdu1312 red and black(BFS)

来源:互联网 发布:linux 任务 暂停 重启 编辑:程序博客网 时间:2024/04/29 07:19

这道题其实就是计算可达的‘.'的个数,当时没想就直接用bfs了,听说dfs更好哦

#include<iostream>#include<queue>#include<cstdio>using namespace std;char map[25][25];int vis[25][25];int d[25][25];int w,h;int dx[]={0,0,1,-1};int dy[]={1,-1,0,0};typedef pair<int,int>m;const int INF=110000000;queue<m>q;int bfs(int x,int y){ int wx=x,wy=y; int sum=1; vis[wx][wy]=1; d[wx][wy]=1; while(!q.empty()){ q.pop(); }  q.push(m(wx,wy)); while(q.size()){    m p=q.front();q.pop(); for(int i=0;i<4;i++){ int nowx=p.first+dx[i]; int nowy=p.second+dy[i]; if(0<=nowx&&nowx<h&&0<=nowy&&nowy<w&&vis[nowx][nowy]==0&&d[nowx][nowy]==INF&&map[nowx][nowy]=='.'){ vis[nowx][nowy]=1; q.push(m(nowx,nowy));d[nowx][nowy]=1; sum++; }  } } return sum;}int main( ){while(~scanf("%d %d",&w,&h)){int x,y,s=0;    if(w==0&&h==0){break;}for(int i=0;i<h;i++){getchar(); for(int j=0;j<w;j++){scanf("%c",&map[i][j]);vis[i][j]=0;d[i][j]=INF;}}for(int i=0;i<h;i++){for(int j=0;j<w;j++){if(map[i][j]=='@'){        x=i;    y=j;//记录起点坐标 //printf("x=%d,y=%d\n",x,y);     break;    }}}s=bfs(x,y); cout<<s<<endl;}return 0;}


0 0
原创粉丝点击