poj_1979 Red and Black
来源:互联网 发布:protty网络验证 编辑:程序博客网 时间:2024/06/06 20:49
这道题是一道搜索题,我用了两种方法都过了,一种是记忆化搜索,另一种是bfs,记忆化搜索用了0MS,bfs用了32MS,我也是新手想用两种方法来解决这道题,我觉得这还是一道比较经典的入门题,很经典,希望大家都能多用几种方法来解决问题,重要的是思维的发散!
这道题的意思就是找从‘@’开始能到的所有‘.’的总和,包括‘@’本身!
//这是记忆化搜索,一直到找不到满足题意为止!
#include <iostream>using namespace std;int m,n;char map[100][100];int dfs(int i,int j){ if(i>=0&&i<n&&j>=0&&j<m) { if(map[i][j]=='#') return 0; map[i][j]='#'; return 1+dfs(i+1,j)+dfs(i-1,j)+dfs(i,j+1)+dfs(i,j-1); } return 0;}int main(){ int i,j; while(cin>>m>>n,m+n) { for(i=0; i<n; i++) for(j=0; j<m; j++) cin>>map[i][j]; for(i=0; i<n; i++) for(j=0; j<m; j++) { if(map[i][j]=='@') cout<<dfs(i,j)<<endl; } } return 0;}
//这是bfs,用队列做,定义一个结构体作为横纵坐标,先把@找到,入队记录下来,然后出队,把记录下来的坐标的上下左右都入队,再重复下去!!!
#include <iostream>#include <queue>#include <cstring>using namespace std;char map[100][100];int flag[100][100];int add_x[]= {0,0,1,-1};int add_y[]= {1,-1,0,0};int n,m;int border(int i,int j){ if(i>=0&&i<m&&j>=0&&j<n) return 1; else return 0;}struct node{ int x,y;};node temp,sign,t;int dfs(){ int count=1; queue<node>s; flag[t.x][t.y]=1; s.push(t); while(!s.empty()) { temp=s.front(); s.pop(); for(int i=0; i<4; i++) { if(!flag[temp.x+add_x[i]][temp.y+add_y[i]]&&border(temp.x+add_x[i],temp.y+add_y[i])) { sign.x=temp.x+add_x[i]; sign.y=temp.y+add_y[i]; flag[sign.x][sign.y]=1; s.push(sign); count++; } } } cout<<count<<endl;}int main(){ int i,j; while(cin>>n>>m,m+n) { for(i=0; i<m; i++) for(j=0; j<n; j++) cin>>map[i][j]; for(i=0; i<m; i++) for(j=0; j<n; j++) { if(map[i][j]=='@') { t.x=i; t.y=j; } if(map[i][j]=='#') flag[i][j]=1; if(map[i][j]=='.') flag[i][j]=0; } dfs(); } return 0;}
0 0
- poj_1979 Red and Black
- 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
- HDU 2844 coins
- malloc/free与new/delete的区别
- <<the architecture of open source applications>> 中关于虚拟机复制与迁移(上)
- PHP及Javascript 正则判断中文
- hdu 4871 Shortest-path tree(最短路+点分治)
- poj_1979 Red and Black
- javascript源码阅读推荐
- MYSQL数据库恢复记录
- leetcode 151: Container With Most Water
- 威威猫系列故事――打地鼠
- 海水淡化膜:海水淡化反渗透膜预处理工艺的重要性
- Mac 下配置 Cocos2d-x 3-x android 的环境,terminal 和 eclipse两种方式
- hpu 2098 素数拆分
- java多线程面试题