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; }