poj_1979 Red and Black
2014-07-24 08:58
369 查看
这道题是一道搜索题,我用了两种方法都过了,一种是记忆化搜索,另一种是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;}
相关文章推荐
- zoj 2165||poj 1979 red and black (dfs)
- POJ 1979 Red and Black
- poj 1979 , zoj 2165 Red and Black【dfs,入门题】
- poj 1979 red and black
- POJ-1979-Red and Black
- poj 1979 Red and Black
- poj 1979 zoj 2165 Red and Black 深搜做法
- zoj 2165 Red and Black (DFs)poj 1979
- POJ 1979 Red and Black(C语言堆栈实现)
- POJ 1979 Red and Black
- poj 1979 Red and Black
- POJ 1979 Red and Black 解题报告
- POJ_1979 Red and Black 迷宫类
- POJ 1979 Red and Black
- POJ1979 Red and Black dfs基础题
- POJ 1979 Red and Black(BFS广度优先搜索)
- poj1979——Red and Black
- poj 1979 Red and Black
- poj 1979 Red and Black
- poj 1979 zoj 2165 Red and Black