POJ 1979 - Red and Black

“.”能走,“#”不能走,“@”为起点,求所有能走到的地方。

BFS:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int w,h;
int dir[4][2]={{0,+1},{-1,0},{0,-1},{+1,0}};
char t[23][23];
bool vis[23][23];
struct type{
	int x,y;
}st,now,next;

int bfs()
{
	int cnt=1;
	queue<type> q;
	q.push(st);
	while(!q.empty())
	{
		now=q.front();q.pop();
		for(int i=0;i<4;i++)  
        {  
            next.x=now.x+dir[i][0] , next.y=now.y+dir[i][1]; //尝试走一步 
            if(vis[next.x][next.y]==0) //如果这一步可以走 
            {
            	vis[next.x][next.y]=1; //将走过的这块tile标记为1
            	q.push(next); 
            	cnt++; //可走的tile计数+1 
            }
        }
	}
	return cnt;
}

int main()
{
	while(scanf("%d%d",&w,&h) && (w*h)!=0)
	{ 
		for(int i=1;i<=h;i++)
		{
			scanf("%s",(t[i]+1));
		}
		
		//将地图转化为相应的标记数组,所有不能走的、走过的tile均标记为1(包括边界以外的地方以及起点),能走的tile都标记为0
		memset(vis,1,sizeof(vis)); 
		for(int i=1;i<=h;i++)
		{
			for(int j=1;j<=w;j++)
			{
				if(t[i][j]=='.') vis[i][j]=0;
				if(t[i][j]=='#') vis[i][j]=1;
				if(t[i][j]=='@') st.x=i,st.y=j,vis[i][j]=1;
			}
		}
		
		int ans=bfs();
		printf("%d\n",ans);
	}
}

 
DFS:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int w,h;
int dir[4][2]={{0,+1},{-1,0},{0,-1},{+1,0}};
char t[23][23];
bool vis[23][23];
struct type{
	int x,y;
}st,next;

void dfs(int x,int y,int &ans)
{
	if(vis[x][y]) return; //如果这个tile走过直接退出函数
	vis[x][y]=1; //把这块tile标记为已走过
	ans++; //计数+1
	for(int i=0;i<4;i++)
	{
		next.x=x+dir[i][0] , next.y=y+dir[i][1]; //走一步
		if(next.x >= 1 && next.x <= h && next.y >= 1 && next.y <= w) //如果走的这一步tile在限定的 w * h 范围内就深搜一下
		{
			dfs(next.x,next.y,ans);
		}
	}
}

int main()
{
	while(scanf("%d%d",&w,&h) && (w*h)!=0)
	{ 
		for(int i=1;i<=h;i++)
		{
			scanf("%s",(t[i]+1));
		}
		
		for(int i=1;i<=h;i++)
		{
			for(int j=1;j<=w;j++)
			{
				if(t[i][j]=='.') vis[i][j]=0;
				if(t[i][j]=='#') vis[i][j]=1;
				if(t[i][j]=='@') st.x=i,st.y=j,vis[i][j]=0;
			}
		}
		
		int ans=0;
		dfs(st.x,st.y,ans);
		printf("%d\n",ans);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值