首页 > 其他 > 详细

HDU 1312 Red and Black-dfs&bfs-(分块)

时间:2015-07-15 13:22:16      阅读:311      评论:0      收藏:0      [点我收藏+]

题意:一个二维数组,给定起点,有些地方能走,有些地方不能走,求从起点出发最多能走过多少点

分析:dfs和bfs都行,注意两者实现的细节差异

dfs代码:

#include<iostream>
using namespace std;
int d[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char a[100][100];
int n,m,tot;
void dfs(int x,int y)
{
	if(a[x][y]=='#') return;
	a[x][y]='#';
	tot++;
	for(int i=0;i<4;i++){
		int dx=x+d[i][0];
		int dy=y+d[i][1];
		if(dx>=0&&dx<m&&dy>=0&&dy<n){
			dfs(dx,dy);
		}
	}
}
int main()
{
	int sx,sy;
	while(cin>>n>>m){
		if(!n&&!m) break;
		tot=0;
		for(int i=0;i<m;i++){
			for(int j=0;j<n;j++){
				cin>>a[i][j];
				if(a[i][j]=='@'){
					sx=i,sy=j;
				}				  
			}
		}
		dfs(sx,sy);
		cout<<tot<<endl;
	} 
}
bfs代码:

#include<iostream>
#include<queue>
using namespace std;
int d[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char a[100][100];
int n,m,tot;
struct node{
	int x,y;
};
queue<node> q;
void bfs()
{
	while(!q.empty()){
		node tmp=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			node tmp2;
			tmp2.x=tmp.x+d[i][0];
			tmp2.y=tmp.y+d[i][1];
			if(tmp2.x>=0&&tmp2.x<m&&tmp2.y>=0&&tmp2.y<n&&a[tmp2.x][tmp2.y]!='#'){
				a[tmp2.x][tmp2.y]='#';
				tot++;
				q.push(tmp2);
			}
		}
	}
}
int main()
{
	while(cin>>n>>m){
		if(!n&&!m) break;
		while(!q.empty()) q.pop();
		tot=0;
		node tmp;
		for(int i=0;i<m;i++)
		  for(int j=0;j<n;j++){
		  	cin>>a[i][j];
		  	if(a[i][j]=='@'){		  			  	   
		  	   tmp.x=i,tmp.y=j;	
				a[i][j]='#';	  	 //  注意这里 
		  	 }
		  }
		  tot=1; // 注意这里 
		  q.push(tmp);
		  bfs();
		  cout<<tot<<endl;
	}
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

HDU 1312 Red and Black-dfs&bfs-(分块)

原文:http://blog.csdn.net/ac_0_summer/article/details/46889655

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!