BFS:
Start Point;
Start search:
When reading the first and leaving the team, the search range is four or eight points (some do not exist). The searched points are in the queue and the duration is + 1 until the read point is equal to the end point;
Code:
#include <iostream>#include <string>#include <cstdio>#include <queue>using namespace std;struct point{int x;int y;int step;}st,ed;int x1,y1,x2,y2;bool visit[10][10];int xx[8] = {1,2,1,2,-1,-2,-1,-2};int yy[8] = {2,1,-2,-1,2,1,-2,-1};void bfs(){memset(visit,false,sizeof(visit));st.x = x1;st.y = y1;st.step = 0;queue <point> p;p.push(st);while(!p.empty()){ed = p.front();p.pop();if(ed.x == x2 && ed.y == y2)break;for(int i = 0; i < 8; i++){st.x = ed.x + xx[i];st.y = ed.y + yy[i];st.step = ed.step + 1;if(!visit[st.x][st.y]&&st.x>0&&st.x<9&&st.y>0&&st.y<9){visit[st.x][st.y] = true;p.push(st);}}}}int main(){char c1,c2,c;while(scanf("%c%d%c%c%d",&c1,&y1,&c,&c2,&y2)!=EOF){x1 = c1 - 'a' + 1;x2 = c2 - 'a' + 1;bfs();printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,y1,c2,y2,ed.step);getchar();}}
DFS:
Perform 8 Class-Oriented Access to each vertex from the starting point and call DFS recursively. The complexity is high. This question is only 8x8, so it is acceptable;
Code:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <string>#include <iomanip>using namespace std;int r[8][2]={{2,1},{1,2},{-1,2},{-2,1}, {2,-1},{1,-2},{-1,-2},{-2,-1} };int num[10][10];void dfs(int x1, int y1, int move){if(x1<=0 || x1>=9 || y1<=0 || y1>=9||move>=num[x1][y1])return ;num[x1][y1] = move;for(int i = 0; i < 8; i++){dfs(x1+r[i][0], y1+r[i][1],move+1);}}int main(int argc, char *argv[]){int x1,y1,x2,y2;char c1,c2,c;while(scanf("%c%d%c%c%d",&c1,&y1,&c,&c2,&y2)!=EOF){x1 = c1 - 'a' + 1;x2 = c2 - 'a' + 1;memset(num,100,sizeof(num));dfs(x1,y1,0);printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,y1,c2,y2,num[x2][y2]);getchar();}return 0;}