Find a way(广搜)

“Y”表示伊芬飞的初始位置。
“M”快速马克起步位置。
“#”禁止道路;
”。的道路。
“@”KCF
样例输入:
4 4
Y.#@

.#…
@…M
4 4
Y.#@

.#…
@#.M
5 5
Y…@.
.#…
.#…
@…M.
#…#
样例输出:
66
88
66

代码:

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
char ax[200][200];
int tag[200][200],sp[200][200];    //数组tag用来标记是否走过,数组sp用来标记需要花的步数
int n,m;
int nest[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct node
{
	int x,y,step;     //坐标和走过的步数 
};
void bfs(int i,int j)
{
	node a,b;
	queue<node>q;
	a.x=i;
	a.y=j;
	a.step=0;
	q.push(a);
	while(!q.empty())
	{
		a=q.front();
		q.pop();
		b.step=a.step+1;
		for(int i=0;i<4;i++)
		{
			b.x=a.x+nest[i][0];
			b.y=a.y+nest[i][1];
			if(ax[b.x][b.y]=='#'||b.x<0||b.x>=n||b.y<0||b.y>=m)     //越界或遇到障碍物 
			continue;
			if(tag[b.x][b.y])     //被标记过的,已经遍历过的 
			continue;
			tag[b.x][b.y]=1;
			sp[b.x][b.y]+=b.step;       //步数相加 
			q.push(b);     //入栈 
		}
	}
}



int main()
{
	
	while(~scanf("%d %d",&n,&m))
	{
		int t=500;
		memset(sp,0,sizeof(sp));
		
		for(int i=0;i<n;i++)
		scanf("%s",ax[i]);     //以字符串的形式输入,单个字符输入容易出错 
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(ax[i][j]=='Y'||ax[i][j]=='M')
				{
					memset(tag,0,sizeof(tag));    //两个人的步数相加,进行2次广搜 
					bfs(i,j);
				}
			}
		}
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(ax[i][j]=='@'&&sp[i][j]<t&&sp[i][j]!=0)
				t=sp[i][j];
			}
		}
		printf("%d\n",t*11);
	}
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/G191018/article/details/88822753