5 28 0 <Strong> question: give an n * N chessboard and give the minimum number of steps from the start point to the end point of the x y coordinate ball. </Strong> Bidirectional BFS code: <Pre class = "brush: java;" >#include <iostream> # Include <cstdio> # Include <queue> # Include <cstring> # Deprecision qq 330 Using namespace std; Int vis1 [qq] [qq]; // number of steps that both mark the path and count Int vis2 [qq] [qq]; Int fx1 [8] = {2,-2,-2, 1, 1,-1,-1 }; Int fx2 [8] = {1,-2,-2 }; Struct node { Int x, y; } Start, end; // start point at both ends of Bidirectional BFS Int sx, sy, ex, ey; Int m; Bool inside (int xx, int yy) // you can determine whether an out-of-bounds occurs. { 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 number of subsequent steps starts from 0. Vis2 [ex] [ey] = 0; While (! Q. empty ()&&! W. empty ()) { Node now, next; Tq = q. size (); // to determine all the queues first While (tq --) { Now = q. front (); Q. pop (); If (inside (now. x, now. y) & vis2 [now. x] [now. y]! =-1) // both ends start through this point .. { Printf ("% d \ n", 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 is... { Printf ("% d \ n", 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 --) // same as above { Now = w. front (); W. pop (); If (inside (now. x, now. y) & vis1 [now. x] [now. y]! =-1) { Printf ("% d \ n", 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 ("% d \ n", 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 ); Scanf ("% d", & sx, & sy, & ex, & ey ); Memset (vis1,-1, sizeof (vis1); // mark as not passed Memset (vis2,-1, sizeof (vis2 )); Dbfs (); } Return 0; } </M & yy <m)> </cstring> </queue> </cstdio> </iostream> </pre> <br> the essence of Bidirectional BFS is to start searching from the start point and end point at the same time. find the shortest path .. <Br> |