码迷,mamicode.com
首页 > 其他好文 > 详细

双向BFS

时间:2015-02-15 20:33:54      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

/*
转自http://blog.csdn.net/custqi/article/details/6455425
感觉对双向广搜写得挺清楚的
*/

1
#include<iostream> 2 #include<cmath> 3 #include<queue> 4 using namespace std; 5 const int maxn = 301; 6 int n; 7 int used[maxn][maxn]; 8 int g[maxn][maxn]; 9 int d[8][2] = { {-2,-1}, {-2,1}, {-1,-2}, {-1,2}, {1,-2}, {1,2}, {2,-1}, {2,1} }; 10 //int x[] = {-2,-2,-1,-1,1,1,2,2}; 11 //int y[] = {-1,1,-2,2,-2,2,-1,1}; 12 struct Point 13 { 14 int x,y; 15 }st,ed; 16 int Check(int x,int y) 17 { 18 return (x>=0 && x<n && y>=0 &&y<n); 19 } 20 int solve() 21 { 22 int sx,sy,tx,ty; //sx,sy 先前结点 tx,ty生成新结点 23 queue<Point>Q; 24 Point curNode,nextNode; 25 memset(used,0,sizeof(used)); 26 //放入起始结点 27 g[st.x][st.y] = 0; 28 used[st.x][st.y] = 1;//由起始结点方向扩展的结点记录值为 1 29 Q.push(st); 30 //放入终止结点 31 g[ed.x][ed.y] = 0; 32 used[ed.x][ed.y] = 2;//由终止结点方向扩展的结点记录值为 2 33 Q.push(ed); 34 //同时放入起始结点和终止结点 进行双向广搜 35 while(!Q.empty()) 36 { 37 curNode = Q.front(); 38 Q.pop(); 39 sx = curNode.x; 40 sy = curNode.y; 41 for(int i=0;i<8;i++) 42 { 43 tx = sx + d[i][0]; 44 ty = sy + d[i][1]; 45 if(!Check(tx,ty)) continue; 46 if(used[tx][ty]==0) //如果used[tx][ty]未访问过 47 { 48 g[tx][ty] = g[sx][sy]+1; //更新在tx ty的值 49 nextNode.x = tx; 50 nextNode.y = ty; 51 used[tx][ty] = used[sx][sy]; // 52 Q.push(nextNode); 53 } 54 else if(used[sx][sy]!=used[tx][ty]) //起始方向与终止方向同时进行后,此时的结点为俩个方向相遇的点,得到结果 55 { 56 return g[sx][sy] + g[tx][ty] + 1; 57 } 58 } 59 } 60 return 0; 61 } 62 int main() 63 { 64 int TestCases; 65 scanf("%d",&TestCases); 66 while(TestCases--) 67 { 68 scanf("%d%d%d%d%d",&n,&st.x,&st.y,&ed.x,&ed.y); 69 printf("%d/n",solve()); 70 } 71 return 0; 72 }

 

双向BFS

标签:

原文地址:http://www.cnblogs.com/usedrosee/p/4293417.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!