Link: knight moves
It is not difficult to study two-way BFs. Like common BFs, two-way BFS only searches at the same time from the start and end points, reducing the search time.
When the two search routes meet, the process ends.
It seems that one year of Baidu's recruitment test is two-way BFS ....
Next, compare the BFS and bidirectional BFS;
BFS
The queue of STL may waste some time.
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <queue>const int N = 310;using namespace std;int mapp[N][N];bool vis[N][N];struct node{ int x,y,ans;};int n;int mv[8][2] = {{1,2},{1,-2},{2,1},{2,-1},{-2,1},{-2,-1},{-1,2},{-1,-2}};void BFS(int sx,int sy,int ex,int ey){ queue<node>q; node t,f; memset(vis,0,sizeof(vis)); f.x = sx; f.y = sy; f.ans = 0; vis[sx][sy] = true; q.push(f); while(!q.empty()) { t = q.front(); q.pop(); if(t.x==ex && t.y==ey) { printf("%d\n",t.ans); return ; } for(int i = 0;i<8;i++) { f.x = t.x + mv[i][0]; f.y = t.y + mv[i][1]; if(!vis[f.x][f.y]&& 0<=f.x && f.x <n && 0<=f.y && f.y<n) { f.ans = t.ans + 1; q.push(f); vis[f.x][f.y] = true; } } }}int main(){ int t,sx,sy,ex,ey; std::ios::sync_with_stdio(false); scanf("%d",&t); while(t--) { scanf("%d",&n); scanf("%d%d",&sx,&sy); scanf("%d%d",&ex,&ey); BFS(sx,sy,ex,ey); } return 0;}
Bidirectional BFS
The time difference is not very big, but theoretically, the time complexity will be reduced several times. If the data is big, the time difference will be obvious.
# Include <iostream> # include <cstdio> # include <cstdlib> # include <cstring> # include <queue> const int n = 310; using namespace STD; int Mapp [N] [N]; int vis [N] [N]; struct node {int X, Y ;}; int N; int MV [8] [2] = {1}, {1,-2}, {2, 1}, {2,-1}, {-2, 1 }, {-2,-1 },{-1}, {-1,-2 }}; int dis [N] [N]; void BFS (INT Sx, int Sy, int ex, int ey) {If (SX = ex & Sy = ey) {printf ("0 \ n"); return;} queue <node> q; node T, F; memset (VIS, 0, siz EOF (VIS); memset (DIS, 0, sizeof (DIS); F. X = SX; F. y = sy; T. X = ex; T. y = ey; vis [SX] [sy] = 1; // the route from the start point is marked as 1 vis [Ex] [ey] = 2; // mark the search route as 2 Q. push (f); q. push (t); While (! Q. empty () {T = Q. front (); q. pop (); For (INT I = 0; I <8; I ++) {f. X = T. X + MV [I] [0]; F. y = T. Y + MV [I] [1]; If (0 <= f. X & F. x <n & 0 <= f. Y & F. Y <n) {If (! Vis [F. x] [F. y]) {dis [F. x] [F. y] = dis [T. x] [T. y] + 1; q. push (f); vis [F. x] [F. y] = vis [T. x] [T. y];} else if (vis [F. x] [F. y]! = Vis [T. x] [T. y]) // encounter the two {printf ("% d \ n", DIS [F. x] [F. y] + dis [T. x] [T. y] + 1); // The point of the encounter will be missed, so we need to add 1 return ;}}} int main () {int T, Sx, Sy, ex, ey; STD: IOS: sync_with_stdio (false); scanf ("% d", & T); While (t --) {scanf ("% d ", & N); scanf ("% d", & Sx, & Sy); scanf ("% d", & Ex, & ey); BFS (sx, sy, ex, ey);} return 0 ;}