HDU 2612

15 篇文章 0 订阅
14 篇文章 0 订阅

点此进入题目:题目链接

思路:开始想用 双向BFS 但是 写着写着不会了,又改用单向BFS。跑两次图,然后找到最小值即可

AC代码:

#include<iostream>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
const int maxn = 205;
const int INF = (1 << 31) - 1;
char maze[maxn][maxn];
int vis[maxn][maxn];
int dist1[maxn][maxn];
int dist2[maxn][maxn];
int n, m;
int X[4] = {1, -1, 0, 0};
int Y[4] = {0, 0, 1, -1};

struct node{
	int x, y;
};
bool check(node now){
	if(now.x < 1 || now.x > n || now.y < 1 || now.y > m || maze[now.x][now.y] == '#'){
		return 0;
	}
	return 1;
}
int BFS(node s, int dist[][maxn]){
	memset(vis, 0, sizeof(vis));
	queue<node> q;
	q.push(s);
	vis[s.x][s.y] = 1;
	dist[s.x][s.y] = 0;
	node front, next;
	while(!q.empty()){
		front = q.front();
		q.pop();
		for(int i = 0; i < 4; i++){
			next.x = front.x + X[i];
			next.y = front.y + Y[i];
			if(check(next) && vis[next.x][next.y] == 0){
				dist[next.x][next.y] = dist[front.x][front.y] + 1;
				vis[next.x][next.y] = 1;
				q.push(next); 
			}
		}
	}
}
int main(){
	while(cin >> n >> m){
		node start, end;
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= m; j++){
				cin >> maze[i][j];
				if(maze[i][j] == 'Y'){
					start.x = i;
					start.y = j;
				}
				if(maze[i][j] == 'M'){
					end.x = i;
					end.y = j;
				}
			} 
		}
		memset(dist1, 0, sizeof(dist1));
		memset(dist2, 0, sizeof(dist2));
		BFS(start, dist1);	
		BFS(end, dist2);
		int ans = INF;
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= m; j++){
				if(ans > dist1[i][j] + dist2[i][j] && dist1[i][j] != 0 && dist2[i][j] != 0 && maze[i][j] == '@'){
					ans = dist1[i][j] + dist2[i][j];
				}
			}
		}
		ans *= 11;
		cout << ans << endl;
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值