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 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 5 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100-101 |
5 0 <strong>: Give a n*n board and give the minimum number of steps to the end of the x y coordinate of the starting point. </strong> bidirectional BFS Code: <pre class= "Brush:java;" > #include <iostream> #include <cstdio> #include <queue> #include <cstring> #define QQ 330 using namespace Std; int vis1[qq][qq]; //Mark path also count step int vis2[qq][qq]; int fx1[8]={2,2,-2,-2,1,1,-1,-1}; int fx2[8]={1,-1,1,-1,2,-2,2,-2}; struct Node { int x,y;} start,end; //bi-directional BFS at both ends of the beginning int Sx,sy,ex,ey; int m; BOOL Inside (int xx,int yy) //Judging out of bounds { if (xx>=0&&yy>=0&&xx<m&&yy<m) return= "true;=" "else=" "false;=" "}=" " Void= "" "dBFS () =" "{=" "int=" "i,tq,tw;=" "queue<node=" ">q,w; //Two queues start.x=sx;start.y=sy; end.x=ex;end.y=ey; q.push (start); w.push (end); vis1[sx][sy]=0; //The following steps are added starting from 0. vis2[ex][ey]=0; while (!q.empty () &&!w.empty ()) { node Now,next; tq=q.size (); //To first judge the entire queue while (tq--) { now=q.front (); q.pop (); if (Inside (NOW.X,NOW.Y) &&VIS2[NOW.X][NOW.Y] !=-1) //Both ends of the beginning are through thisPoint.. { printf ("%dn", Vis1[now.x][now.y]+vis2[now.x][now.y]); return; } for (i=0;i<8;i++) { next.x=now.x+fx1[i]; next.y=now.y+fx2[i]; if (Inside (NEXT.X,NEXT.Y) &&VIS2[NEXT.X][NEXT.Y]!=-1) //important, because the odd step when ... { & nbsp; printf ("%dn", vis1[now.x][ NOW.Y]+1+VIS2[NEXT.X][NEXT.Y]); Return } if (Inside (NEXT.X,NEXT.Y) &&vis1[next.x][ Next.y]==-1) { vis1[next.x][ next.y]=vis1[now.x][now.y]+1; Q.push (next); } } } tw=w.size (); while (tw--) /Ibid. { Now=w.front (); w.pop (); if (Inside (NOW.X,NOW.Y) &&VIS1[NOW.X][NOW.Y] !=-1) { printf ("%dn", Vis1[now.x][now.y]+vis2[now.x][now.y]); return; } for (i=0;i<8;i++) { next.x=now.x+ Fx1[i]; next.y=now.y+fx2[i]; if (Inside (NEXT.X,NEXT.Y) &&vis1[next.x][next.y]!=-1) { printf ("%dn", Vis2[now.x][now.y]+1+vis1[next.x][next.y]); Return } if (Inside (NEXT.X,NEXT.Y) &&vis2[next.x][ Next.y]==-1) { vis2[next.x][next.y]=vis2[now.x][now.y]+1; W.push (next); } } int main () { int T; scanf ("%d", &t); while (t--) { scanf ("%d", &m); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%d%d%d%d", &sx,&sy,&ex,&ey); memset (vis1,-1,sizeof (VIS1)); // Mark as not traversed memset (Vis2,-1,sizeof (VIS2)); dbfs (); &NBSP;&NBSP;&NBSP;&NBSP} return 0; } </m&&yy<m) ></cstring></queue></cstdio></iostream></pre><br The essence of the > bidirectional BFS is to start the search from the start point and find the shortest path when both ends are found. <br><br> |