Red and Black
来源:互联网 发布:手机影集制作软件 编辑:程序博客网 时间:2024/06/12 05:52
题目链接:http://poj.org/problem?id=1979
本题可以用bfs和dfs,第一个是bfs,要注意控制越界问题,这道题没有终点,因此只要覆盖整个地图就可以,所以dfs和bfs都可以,bfs我采用了两个数组,一个数组用来记录地图,一个数组用来标记,而且还要注意输入时用scanf会读入回车,因此选择cin读入,就没有这种情况.dfs就是按照正常步骤进行但这道题似乎DFS更加简单,只要控制退出条件就可以。
BFS
#include<cstdio>#include<iostream>#include<queue>#include<cstring>using namespace std;const int dx[4] = {1,0,-1,0};const int dy[4] = {0,1,0,-1};const int maxn = 30;bool vis[maxn][maxn];bool vist[maxn][maxn];char mp[maxn][maxn];struct node{ int x,y;};node New,now;node s;int t;int w,h;queue<node> q;void bfs(){ q.push(s); vis[s.x][s.y]=true; t=1; while(!q.empty()) { now=q.front(); q.pop(); //t++放在循环内外都一样,因为弹出和入队都一样。起点也是黑格子。所以要计数 for(int i=0; i<4; i++) { New.x = now.x+dx[i]; New.y = now.y+dy[i]; if(vist[New.x][New.y]&&!vis[New.x][New.y]&&New.x>0&&New.y>0&&New.x<=h&&New.y<=w) { q.push(New); vis[New.x][New.y]=true; t++; } } } cout<<t<<endl;}int main(){ while(scanf("%d%d",&w,&h),w&&h) { t=0; memset(vis,false,sizeof(vis)); memset(vist,false,sizeof(vist)); for(int i=1; i<=h;i++) { for(int j=1;j<=w;j++) { cin>>mp[i][j]; } } for(int i=1; i<=h; i++) { for(int j=1; j<=w; j++) { if(mp[i][j]=='@') { s.x=i; s.y=j; } if(mp[i][j]=='.') vist[i][j]=true; } } bfs(); } return 0;DFS
#include<cstdio>#include<cstring>#include<iostream>using namespace std;const int maxn=30;char mp[maxn][maxn];bool vis[maxn][maxn];int step;int h,w;void dfs(int x,int y){ if(x<=0||x>h) return; if(y<=0||y>w) return; if(mp[x][y]=='#'||vis[x][y]) return; vis[x][y]=true; step++; dfs(x+1,y); dfs(x-1,y); dfs(x,y+1); dfs(x,y-1);}int main(){ int x,y; while(cin>>w>>h,w&&h) { memset(vis,false,sizeof(vis)); memset(mp,'#',sizeof(mp)); for(int i=1; i<=h; i++) { for(int j=1; j<=w; j++) { cin>>mp[i][j]; } } for(int i=1; i<=h; i++) { for(int j=1; j<=w; j++) { if(mp[i][j]=='@') { x = i; y = j; } } } step = 0; dfs(x,y); cout << step << endl; } return 0;}
0 0
- Red and Black
- red and black
- HDUOJ1312 Red and Black
- Red and Black
- red and black
- Red and Black
- HDOJ Red and Black
- HDU1312( Red and Black )
- Red and Black
- hdu1312 Red and Black
- 深搜:Red and Black
- 1038 Red and Black
- HDU1312 Red and Black
- HDU Red and Black
- Red and Black
- HDU1312:Red and Black
- 1001Red and Black
- Red and Black 搜索
- ZooKeeper的同步流程
- nyoj237 游戏高手的烦恼(最小点覆盖)
- 认识User-Agent
- jQuery选择器
- 一些ps会遇到的问题
- Red and Black
- 利用sharepoint 创建轻量型应用之配置传入电子邮件!
- Java泛型
- [BZOJ1059] [ZJOI2007] 矩阵游戏 - 二分图匹配
- Android之Activity的生命周期
- C++——多次free和delete导致错误
- 字符串函数的实现
- 未重新服务器而导致的错误java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is
- c++第三次实验——作业