This problem can be used in BFs. I tried to write a bidirectional BFs.
Unidirectional BFs, 450 + MS, bidirectional 300 + MS
# Include <iostream> # include <queue> # include <memory. h> using namespace STD; struct coordinate {int X, Y; int step ;}; int dir [8] [2] ={{ 1, 2}, {1, -2}, {-1, 2}, {-1,-2}, {2, 1}, {2,-1}, {-2, 1 }, {-2,-1 }}; int isvisit [301] [301]; int step [301] [301]; coordinate goal, start; int Board; void BFS (); int main () {int N; CIN> N; while (n --) {memset (isvisit, 0, sizeof (isvisit); memset (step, 0, sizeof (STEP); CIN> boar D; CIN> Start. x> Start. y; start. step = 0; isvisit [start. x] [start. y] = 1; CIN> goal. x> goal. y; goal. step = 0; isvisit [goal. x] [goal. y] = 2; BFS ();} return 0;} void BFS () {coordinate P, next; queue <coordinate> q1; queue <coordinate> Q2; P = start; q1.push (p); P = goal; q2.push (GOAL); While (! Q1.empty () {P = q1.front (); q1.pop (); If (P. X = goal. X & P. y = goal. y) {cout <p. step <Endl; return ;}for (INT I = 0; I <8; I ++) {next. X = P. X + dir [I] [0]; next. y = P. Y + dir [I] [1]; next. step = P. step + 1; if (next. x> = 0 & next. x <Board & next. y> = 0 & next. Y <board) {If (isvisit [next. x] [next. y] = 0) {isvisit [next. x] [next. y] = 1; step [next. x] [next. y] = next. step; q1.push (next);} else if (isvisit [next. x] [next. y] = 2) {cout <next. step + step [next. x] [next. y] <Endl; return ;}} P = q2.front (); q2.pop (); For (INT I = 0; I <8; I ++) {next. X = P. X + dir [I] [0]; next. y = P. Y + dir [I] [1]; next. step = P. step + 1; if (next. x> = 0 & next. x <Board & next. y> = 0 & next. Y <board) {If (isvisit [next. x] [next. y] = 0) {isvisit [next. x] [next. y] = 2; step [next. x] [next. y] = next. step; q2.push (next);} else if (isvisit [next. x] [next. y] = 1) {cout <next. step + step [next. x] [next. y] <Endl; return ;}}}}}