【题解】AOJ 0558 Cheese(BFS)

AOJ 0558 Cheese


https://vjudge.net/problem/Aizu-0558

题意

有一只老鼠要吃奶酪,现在有n个奶酪,编号为1~n,小老鼠从起点要按顺序依次到达奶酪所在的点并吃掉,求最短所需步数。

细则:

  • 只能上下左右走
  • 必须要按1~n的顺序
  • "S"为起点,"X"为阻挡物,"1~n"为第 i 个奶酪所在点

输入:第一行三个整数,分别为高h,宽w,奶酪个数。
输出:最小步数。

思路:写一个bfs求两点间最短路,然后依次换起点终点,详细看代码。


#include<iostream>
#include<cstring>
#include<queue>

using namespace std;

const int INF = 0x3f3f3f3f;
const int Maxn = 1000 + 10;
char mp[Maxn][Maxn];
int h, w, N;
int dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1};//方向
int sx, sy, gx, gy;
typedef pair <int, int> P;	//方便记录坐标
int d[Maxn][Maxn];		//用来记录每个点到起点的距离

int bfs(){
	
	queue <P> que;
	memset(d, INF, sizeof(d));		//初始化
	
	que.push(P(sx, sy));	//push起点
	d[sx][sy] = 0;			//该点到起点距离为0
	
	while(que.size()){
		P p = que.front();
		que.pop();
		if(p.first == gx && p.second == gy)	//到达终点,结束循环
			break;
		for(int i = 0; i < 4; i++){
			int nx = p.first + dir[i][0];
			int ny = p.second + dir[i][1];
			if(nx >= 0 && nx < h && ny >= 0 && ny < w && mp[nx][ny] != 'X'//判断该点是否能走
									&& d[nx][ny] == INF){	//还没走过的点
				que.push(P(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[gx][gy];
}

P n[9];	//用于记录第 i 个奶酪的坐标
int main(){
	
	cin >> h >> w >> N;
	for(int i = 0; i < h; i++)
		for(int j = 0; j < w; j++){
			cin >> mp[i][j];
			if(mp[i][j] == 'S'){	//记录起点坐标
				sx = i;sy = j;
			}
			if(mp[i][j] <= '9' && mp[i][j] >= '1'){//奶酪坐标
				n[mp[i][j] - '1'].first = i;
				n[mp[i][j] - '1'].second = j;
			}
		}
	int sum = 0;
	for(int i = 0; i < N; i++){
		
		gx = n[i].first;
		gy = n[i].second;
		sum += bfs();
		sx = gx;sy = gy;	//终点变起点
	}
	cout << sum << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值