题意:模仿中国象棋的马走的方式,求从起点到终点的最少步数。。。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int maze[10][10]; int dir[8][2] ={{-2,-1},{-2,1},{2,-1},{2,1},{1,2},{1,-2},{-1,2},{-1,-2}}; int x1,x2,y2,y1; void dfs(int x,int y,int step) { if (x == x2 && y == y2) return ; for (int i = 0 ; i < 8 ; i++) { int nx = x + dir[i][0]; int ny = y + dir[i][1]; if (nx >= 0 && nx <=7 && ny >= 0 && ny <= 7 && (maze[nx][ny] == -1|| maze[nx][ny] > step)) { maze[nx][ny] =step ; dfs(nx,ny,step+1); } } } int main() { char str1[5],str2[5]; while (scanf("%s%s",str1,str2) != EOF ) { memset(maze,-1,sizeof(maze)); x1 = str1[0]-97,x2 = str2[0]-97; y1 = str1[1]-49,y2 = str2[1]-49; maze[x1][y1] = 0 ; dfs(x1,y1,1); printf("To get from %s to %s takes %d knight moves.\n",str1,str2,maze[x2][y2]); } return 0; }