手打代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 #include <bits/stdc++.h> using namespace std;int a[305 ][305 ];int xy[50005 ][3 ];int b[305 ][305 ];int dx[4 ]={0 ,1 ,0 ,-1 };int dy[4 ]={1 ,0 ,-1 ,0 };int m,p=0 ;struct node { int nx,ny,s; }; void bfs (int sx,int sy) { queue<node>q; q.push ({sx,sy,0 }); b[sx][sy]=1 ; while (q.size ()){ node tmp=q.front (); q.pop (); if (a[tmp.nx][tmp.ny]==0 ){ cout<<tmp.s; exit (0 ); } for (int i=1 ;i<=m;i++){ if (xy[i][2 ]<=tmp.s+1 ){ b[xy[i][0 ]][xy[i][1 ]]=2 ; b[xy[i][0 ]-1 ][xy[i][1 ]]=2 ; b[xy[i][0 ]+1 ][xy[i][1 ]]=2 ; b[xy[i][0 ]][xy[i][1 ]-1 ]=2 ; b[xy[i][0 ]][xy[i][1 ]+1 ]=2 ; } else break ; } for (int i=0 ;i<4 ;i++){ int tx=tmp.nx+dx[i]; int ty=tmp.ny+dy[i]; if (tx>=0 &&ty>=0 &&b[tx][ty]==0 ){ b[tx][ty]=1 ; q.push ({tx,ty,tmp.s+1 }); } } } } int main () { cin>>m; for (int i=1 ;i<=m;i++){ for (int j=0 ;j<3 ;j++){ cin>>xy[i][j]; } if (xy[i][0 ]-1 >=0 ){ a[xy[i][0 ]-1 ][xy[i][1 ]]=1 ; } if (xy[i][1 ]-1 >=0 ){ a[xy[i][0 ]][xy[i][1 ]-1 ]=1 ; } a[xy[i][0 ]][xy[i][1 ]]=1 ; a[xy[i][0 ]+1 ][xy[i][1 ]]=1 ; a[xy[i][0 ]][xy[i][1 ]+1 ]=1 ; } bfs (0 ,0 ); cout<<"-1" ; return 0 ; }
AI分析 流星雨问题:给定若干流星坠落的时间与位置,坠落后该格及其上下左右四格永远不能停留,求从原点出发最早何时能到达安全位置。代码用 BFS 按步数扩展,每扩展一层前,先根据到达时间把被砸毁的格子标记为不可走,再向四个方向推进。第一次走到永远不会被砸的格子时输出步数;队列为空仍未找到则输出 -1。这里的重点是时间与占用状态的对应关系:走第 s 步时只能进入在 s 时刻之前没有被砸的位置。若用按时间预处理的数组,需要正确定义无穷大的初值,否则会误判安全格。
还有一点,起点如果本身已经被砸毁,就无路可走,需要在一开始判掉。用步数等于时间这一约定,能让每次扩展都对应一秒,避免时间与层数错位。