CSU 1726-你经历过绝望吗?两次!(BFS+剪枝)

F - 你经历过绝望吗?两次!
Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%lld & %llu

Description

4月16日,日本熊本地区强震后,受灾严重的阿苏市一养猪场倒塌,幸运的是,猪圈里很多头猪依然坚强存活。当地15名消防员耗时一天解救围困的“猪坚强”。不过与在废墟中靠吃木炭饮雨水存活36天的中国汶川“猪坚强”相比,熊本的猪可没那么幸运,因为它们最终还是没能逃过被送往屠宰场的命运。
我们假设“猪坚强”被困在一个N*M的废墟中,其中“@”表示“猪坚强”的位置,“.”表示可以直接通过的空地,“#”表示不能拆毁的障碍物,“*”表示可以拆毁的障碍物,那么请问消防员至少要拆毁多少个障碍物,才能从废墟中救出“猪坚强”送往屠宰场?(当“猪坚强”通过空地或被拆毁的障碍物移动到废墟边缘时,视作被救出废墟)

Input

多组数据,第一行有一个整数T,表示有T组数据。(T<=100)
以下每组数据第一行有两个整数N和M。(1<=N,M<=100)
接着N行,每行有一个长度为M的字符串。

Output

一个整数,为最少拆毁的障碍物数量,如果不能逃离废墟,输出-1。

Sample Input

3
3 3
###
#@*
***
3 4
####
#@.*
**.*
3 3
.#.
#@#
.#.

Sample Output

1
0
-1
题意:
找出一条最短的路出到边界。
思路:
这题一开始以为不会超时,结果写完给你一个TLE,最后想到,bfs是以次数为关键的,而且之所以超时是因为我拓展的枝条太多了,而且有些路是重复走的,所以记录一下每个地方最快到达就行了,如果大于最小值,我不如直接在最小值拓展,还用你绕路走的路吗。
AC代码:
#include<iostream>
#include<set>
#include<map>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int INF=0x3f3f3f3f;
typedef long long LL;
const int N=100000+1000;
#define T 100+50
int r,c,ans,tarx,tary;
char s[T][T];
int fx[][2] = {{1,0},{0,1},{-1,0},{0,-1}};

struct node
{
	int x,y,cnt;
	node(){}
	node(int _1,int _2,int _3):x(_1),y(_2),cnt(_3){}
	bool operator<(const node& b)const{
		return cnt>b.cnt;
	}
};
priority_queue<node> q;

void BFS()
{
	map< pair<int,int>,int > mp;
	while(!q.empty())q.pop();
	q.push(node(tarx,tary,0));
	mp[make_pair(tarx,tary)] = 0;
	node p;
	while(!q.empty())
	{
		p = q.top();q.pop();
		if(p.x==0||p.x==r-1||p.y==0||p.y==c-1){
			ans = p.cnt;
			break;
		}
		for(int i=0;i<4;++i){
			int tx=p.x+fx[i][0],
				ty=p.y+fx[i][1];
			bool flag = false;
			pair<int,int> pir(tx,ty);
			if(tx>=0&&tx<r&&ty>=0&&ty<c&&s[tx][ty]!='#'){
				int tmp = 0;
				if(mp.count(pir)!=0)flag=true;
				if(s[tx][ty]=='*')tmp++;
				if(mp[pir]>p.cnt+1||!flag)
					q.push(node(tx,ty,p.cnt+tmp)),mp[pir]=p.cnt+tmp;
			}
		}
	}
}

int main()
{
#ifdef cdzsc
	freopen("in.txt","r",stdin);
#endif
	int n,m,i,j,k;
	scanf("%d",&n);
	while(n--)
	{
		ans = INF;
		scanf("%d%d",&r,&c);
		for(i=0;i<r;++i){
			for(j=0;j<c;++j){
				scanf(" %c",&s[i][j]);
				if(s[i][j]=='@'){
					tarx = i;tary = j;
				}
			}
		}
		BFS();
		if(ans==INF)ans=-1;
		printf("%d\n",ans);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值