题目见zoj 1091
使用宽度搜索优先来求解,这个算法已经忘记的差不多了,所以写出来的代码很罗嗦,看起来很不清晰。
好像还可以直接用公式或者神经网络算法求解,详见Knight's Tour
/* zoj 1091 Knight Moves */ #include <stdio.h> #include <string.h> #define MAX 100 #define BOARDSIZE (8+1) struct queueStruct{int x;int y;int step; }queue[MAX],tempQueue; int front; int rear; int minStep; int isVisited[BOARDSIZE][BOARDSIZE]; const int searchTable[8][2] = {{-2,-1},{-1,-2},{-2,1},{-1,2},{1,2},{2,1},{1,-2},{2,-1}}; int bfs(int startx, int starty, int endx, int endy, int step);int main(void) {char src[3],des[3];int startx, starty, endx, endy;while(scanf("%s %s",src,des) == 2){memset(isVisited,0,sizeof(isVisited));memset(queue,0,sizeof(queue));front = rear = 0;startx = src[0] - 'a' + 1;starty = src[1] - '0';endx = des[0] - 'a' + 1;endy = des[1] - '0';bfs(startx,starty,endx,endy,0);printf("To get from %s to %s takes %d knight moves.\n",src,des,minStep);}return 0; } int bfs(int startx, int starty, int endx, int endy, int step) {int i;struct queueStruct q;if(startx == endx && starty == endy){minStep = step;return 0;}isVisited[startx][starty] = 1;tempQueue.x = startx;tempQueue.y = starty;tempQueue.step = step;queue[rear++] = tempQueue;while(front < rear){tempQueue = queue[front++];for(i = 0; i < BOARDSIZE; i++){/* q = tempQueue;*/q.x = tempQueue.x + searchTable[i][0];q.y = tempQueue.y + searchTable[i][1];q.step = tempQueue.step + 1;if(q.x < 1 || q.x > 8 || q.y < 1 || q.y > 8 ||isVisited[q.x][q.y])continue;if(q.x == endx && q.y == endy){minStep = q.step;return 0;}queue[rear++] = q;isVisited[q.x][q.y] = 1;}}return 0; }