HDU--2612.Find a way (BFS)

HDU--2612.Find a way (BFS),第1张

Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.

Input

The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’    express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF

Output

For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.

Input

4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
Output

66
88
66
 

本题的思路:

由两个起点分别bfs一遍,然后看到哪个kfc的距离之和最短

scanf(" %c", &a);

scanf格式化字符串中的空格会匹配任意多个空白字符,所以上面只会读取缓冲区中的第一个非空白字符,而跳过任何空白字符,即使缓冲区中一个空白字符都没有,也不会因此出错。


所以推荐在明确不需要读入空白字符的时候使用这种方式,这样可以防止出错读到了前一行的换行符

C语言scanf格式化字符串中%c的使用建议_Shane Zhang的博客-CSDN博客_scanf(%c)

如果搜到的是kfc那么怎么判断两个kfc是同一个kfc呢?

1.我们可以用结构体来存储,kfc的坐标,写个重载。


那么sort一下就一定是同一个kfc了(sort太慢了),但是也可以AC就是不是很好的做法

2.直接再开个二维数组来存储(完美)

while(~scanf("%d%d",&n,&m))

不写~就会时间超限

 sort重载来写:

#include
#include
#include
#include
#include
using namespace std;
char g[210][210];
int d[210][210];
int n,m;
typedef long long ll;
typedef pairPII;
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};
int f; 
int cnt1,cnt2;

struct node
{
    int x,y,d;	
    bool operator<(const node&t)
    {
    	if(x==t.x)
    	return yq;
	q.push(x);
	memset(d,0,sizeof(d));
	d[x.first][x.second]=0;
//	cout<=0&&ny>=0&&nx>g[i][j];
//				printf("%c........",&g[i][j]);
//				if(g[i][j]=='Y')
//				{
//					st1={i,j};
//					
//					
//				}
//				if(g[i][j]=='M')
//				{
//				//	cout<kfc1[i].d+kfc2[i].d) 
			{
				ans=kfc1[i].d+kfc2[i].d;
			} 
		}
		cout<

 二维数组来写

#include
#include
#include
#include
#include
#include
using namespace std;
char g[210][210];
int d[210][210];
int kfc[210][210];
int book[210][210];


int n,m;
typedef long long ll;
typedef pairPII;
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};

void bfs(PII x)
{
	queueq;
	q.push(x);
	memset(d,0,sizeof(d));
    memset(book,0,sizeof(book));
	book[x.first][x.second]=1;
	
	while(q.size())
	{
		PII t=q.front();
		q.pop();
		
		
		for(int i=0;i<4;i++)
		{
			int nx=dx[i]+t.first;
			int ny=dy[i]+t.second;
			if(nx>=0&&ny>=0&&nx

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/634781.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-16
下一篇 2022-04-16

发表评论

登录后才能评论

评论列表(0条)