hdu 1241 bfs or dfs

http://acm.hdu.edu.cn/showproblem.php?pid=1241

 

基本没什么做过bfs,所以尝试做做,看了一个课件后才基本明白bfs原理

ps:课件网址:http://wenku.baidu.com/view/3cc5ea6c58fafab069dc02d8.html

//================================================ //hdu 1241 bfs //1241 15MS 248K 893 B C++ //================================================ #include<iostream> using namespace std; #include<queue> char map[110][110]; int d[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; struct point { int a,b; }t; void bfs(int i,int j) { int k; queue<point> q; t.a=i,t.b=j; q.push(t); map[i][j]='*'; while(!q.empty()) { t=q.front(); q.pop(); i=t.a,j=t.b; for(k=0;k<8;k++) { int ii=i+d[k][0],jj=j+d[k][1]; t.a=ii,t.b=jj; if(map[ii][jj]=='@') { q.push(t); map[ii][jj]='*'; } } } } int main() { freopen("a.txt","r",stdin); int n,m; while(scanf("%d%d",&n,&m)&&(n+m)) { memset(map,0,sizeof(map)); int i,j; int cnt=0; for(i=1;i<=n;i++) //for(j=1;j<=m;j++) scanf("%s",map[i]+1); //或者cin>>map[i][j]; for(i=1;i<=n;i++) for(j=1;j<=m;j++) if(map[i][j]=='@') { bfs(i,j); cnt++; } printf("%d/n",cnt); } return 0; }

**********************************************************************************************

DFS

//================================================ //hdu 1241 dfs //1241 15MS 304K 619 B C++ //================================================ #include<iostream> using namespace std; char map[110][110]; int n,m; int d[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; void dfs(int i,int j)//每次找出一块油田 { map[i][j]='*'; for(int k=0;k<8;k++) { int ii=i+d[k][0],jj=j+d[k][1]; if(map[ii][jj]=='@') { dfs(ii,jj); } } } int main() { //freopen("a.txt","r",stdin); while(scanf("%d%d",&n,&m)&&(n+m)) { int i,j,cnt=0; for(i=1;i<=n;i++) for(j=1;j<=m;j++) cin>>map[i][j]; for(i=1;i<=n;i++) for(j=1;j<=m;j++) { if(map[i][j]=='@') { cnt++; dfs(i,j); } } printf("%d/n",cnt); } return 0; }

你可能感兴趣的:(c,struct)