双向BFS

直接上例题吧(md,刚刚写了一大堆,没保存wc,现在没心情了)

 1 #include<bits/stdc++.h>
 2 #define maxn 2010
 3 using namespace std;
 4 
 5 int l,n,sx,sy,mx,my,vis[maxn][maxn],dis[maxn][maxn],zz;
 6 
 7 struct node{
 8     int x,y;
 9 };
10 node t,u,v,w;
11 
12 int dx[8]={1,1,-1,-1,2,2,-2,-2};
13 int dy[8]={2,-2,2,-2,1,-1,1,-1};
14 
15 void bfs(int x,int y,int cx,int cy){
16     memset(vis,0,sizeof(vis));
17     memset(dis,0,sizeof(dis));
18     queue<node>q1;
19     queue<node>q2;
20     zz=1;
21     if(x==cx&&y==cy){
22         cout<<"0"<<endl;
23         return ;
24     }
25     t.x=x;
26     t.y=y;
27     q1.push(t);
28     vis[t.x][t.y]=1,dis[t.x][t.y]=0;
29     u.x=cx;
30     u.y=cy;
31     q2.push(u);
32     vis[u.x][u.y]=2,dis[u.x][u.y]=0;
33     while(!q1.empty()&&!q2.empty()){
34         if(zz==1){
35             v=q1.front();
36             q1.pop();
37         }
38         else {
39             v=q2.front();
40             q2.pop();
41         }
42         for(int i=0;i<8;i++){
43             w.x=v.x+dx[i];
44             w.y=v.y+dy[i];
45             if(w.x>=1&&w.y<=n&&w.y>=1&&w.y<=n) {
46                 if(!vis[w.x][w.y]){
47                     vis[w.x][w.y]=zz;
48                     dis[w.x][w.y]=dis[v.x][v.y]+1;
49                     if(zz==1) q1.push(w);
50                     else q2.push(w);
51                 }
52                 else {
53                     if(vis[w.x][w.y]==zz) continue;
54                     else{
55                         cout<<dis[v.x][v.y]+dis[w.x][w.y]+1<<endl;
56                         return ;
57                     }
58                 }
59             }
60         }
61         if(zz==1) zz=2;
62         else zz=1;
63     }
64 }
65 
66 int main(){
67     cin>>l>>n;
68     for(int i=1;i<=l;i++){
69         cin>>sx>>sy>>mx>>my;
70         bfs(sx,sy,mx,my);
71     }
72     return 0;
73 }

md,自己看吧

 

posted @ 2021-10-02 16:02  ツキユレ  阅读(48)  评论(0编辑  收藏  举报