【BFS】POJ3669-Meteor Shower

【思路】

预处理时先将陨石落到各点的最短时间纪录到数组中,然后在时间允许的范围内进行广搜。一旦到某点永远不会砸到,退出广搜。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<queue>
 6 using namespace std;
 7 const int MAXN=300+50;
 8 const int INF=0x7f7f7f7f;
 9 struct Rec
10 {
11     int x,y,t;
12 };
13 int m;
14 int map[MAXN][MAXN],vis[MAXN][MAXN];
15 int dx[5]={0,0,1,-1,0};
16 int dy[5]={1,-1,0,0,0};
17 
18 int bfs()
19 {
20     queue <Rec> que;
21     Rec temp;
22     temp.x=temp.y=temp.t=0;
23     que.push(temp);
24     vis[0][0]=1;
25     
26     while (!que.empty())
27     {
28         Rec head=que.front();
29         que.pop();
30         for (int i=0;i<4;i++)
31         {
32             int tx=head.x+dx[i],ty=head.y+dy[i],tt=head.t+1;
33             if (tx<0 || ty<0 || vis[tx][ty]==1 || map[tx][ty]<=tt) continue;
34             vis[tx][ty]=1;
35             
36             temp.x=tx;temp.y=ty;temp.t=tt;
37             que.push(temp);
38             if (map[tx][ty]==INF)
39             {
40                 return tt;
41             }
42         }
43     }
44     return -1;
45 }
46 
47 int main()
48 {
49     scanf("%d",&m);
50     memset(map,INF,sizeof(map));
51     memset(vis,0,sizeof(vis));
52     for (int i=0;i<m;i++)
53     {
54         int x,y,t;
55         scanf("%d%d%d",&x,&y,&t);
56         for (int i=0;i<5;i++)
57             if (x+dx[i]>=0 && y+dy[i]>=0 && map[x+dx[i]][y+dy[i]]>t) map[x+dx[i]][y+dy[i]]=t;
58     }
59 
60     if (map[0][0]==0) cout<<-1<<endl;
61         else if (map[0][0]==INF) cout<<0<<endl;
62               else cout<<bfs()<<endl;
63     64     return 0;
65 }
原文地址:https://www.cnblogs.com/iiyiyi/p/4712961.html