Problem Link: POJ1915 Knight Moves.
Test Instructions Description: Enter the number of test cases, enter the board size, enter two points in the chess board, the minimum number of steps that the horse jumps from one point to another.
Problem Analysis: A typical BFS problem. In the BFS search process, the horse skipped the point no longer to jump, because this time it is not possible to jump more than the last step of less.
program, a queue is used to hold the middle node, but it needs to be emptied each time it runs out.
The AC C + + language program is as follows:
/* POJ1915 Knight Moves * * #include <cstdio> #include <cstring> #include <queue>using namespace std;# Define MAXN 300#define directsize 8struct Direct {int drow; int Dcol;} Direct[directsize] = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2,-1}, {-1,-2}, {-1 N, L;int Startcol, StartRow, Endcol, endrow;int ans;struct node {int row; int col; int level;}; Queue<node> q;void BFs () {while (!q.empty ()) Q.pop (); memset (grid, 0, sizeof (GRID)); Grid[startrow][startcol] = 1; Ans = 0; node start; Start.row = StartRow; Start.col = Startcol; Start.level = 0; Q.push (start); while (!q.empty ()) {node front = Q.front (); Q.pop (); if (Front.row = = Endrow && Front.col = = Endcol) {ans = front.level; Break } for (int i=0; i<directsize; i++) {int nextrow = Front.row + direct[i].drow; int nextcol = Front.col + diRect[i].dcol; if (0 <= nextrow && nextrow < l && 0 <= nextcol && nextcol < L) if (grid[ Nextrow][nextcol] = = 0) {Grid[nextrow][nextcol] = 1; Node V; V.row = NextRow; V.col = Nextcol; V.level = Front.level + 1; Q.push (v); }}}}int Main (void) {scanf ("%d", &n); while (n--) {scanf ("%d%d%d%d%d", &l, &startrow, &startcol, &endrow, &endcol); BFS (); printf ("%d\n", ans); } return 0;}
POJ1915 Knight Moves