KuangBin 专题一:简单搜索 Find a way

题目链接:
传送门

#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int N = 205;

int op[4][2]= {{0,1},{0,-1},{1,0},{-1,0}},n,m,Yx,Yy,Mx,My,theend[N][2],ans1[N][N],ans2[N][N];
char theMap[N][N];

struct node {
	int x,y;
};

//判断是否在边界内
bool intheMap(int x,int y) {
	return x>=0&&y>=0&&x<n&&y<m;
}

//第一个人进行bfs
int bfs1(int x,int y) {
	memset(ans1, 0, sizeof(ans1));
	ans1[x][y] = 1;
	queue<node> q;
	node start = {x,y};
	q.push(start);
	while(!q.empty()) {
		node cur = q.front();
		q.pop();
		for(int i=0; i<4; i++) {
			int curX = cur.x+op[i][0];
			int curY = cur.y+op[i][1];
			if(intheMap(curX,curY)&&theMap[curX][curY]!='#'&&!ans1[curX][curY]) {
				ans1[curX][curY]=ans1[cur.x][cur.y]+1;
				node news= {curX,curY};
				q.push(news);
			}
		}
	}
}

//第二个人进行bfs
int bfs2(int x,int y) {
	memset(ans2, 0, sizeof(ans2));
	ans2[x][y] = 1;
	queue<node> q;
	node start = {x,y};
	q.push(start);
	while(!q.empty()) {
		node cur = q.front();
		q.pop();
		for(int i=0; i<4; i++) {
			int curX = cur.x+op[i][0];
			int curY = cur.y+op[i][1];
			if(intheMap(curX,curY)&&theMap[curX][curY]!='#'&&!ans2[curX][curY]) {
				ans2[curX][curY]=ans2[cur.x][cur.y]+1;
				node news= {curX,curY};
				q.push(news);
			}
		}
	}
}

int main() {
	int sx, sy, tx, ty, x, y, ans;
	while(scanf("%d%d", &n, &m) != EOF) {
		ans = 999999999;
		for(int i = 0; i < n; i++) scanf("%s", theMap[i]);
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < m; j++) {
				if(theMap[i][j] == 'Y') sx = i, sy = j;
			}
		}
		bfs1(sx, sy);
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < m; j++) {
				if(theMap[i][j] == 'M') sx = i, sy = j;
			}
		}
		bfs2(sx, sy);
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < m; j++) {
				if(theMap[i][j] == '@' && ans1[i][j] && ans2[i][j]) ans = min(ans, (ans1[i][j] + ans2[i][j] - 2) * 11);
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}

这道题是用两个BFS来搜索,找到Y和M的点,然后对这几个点进行bfs搜出他们到目标点,然后找到它们的最短路径然后把总路径乘11。最后输出答案。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值