思路:DFS就是从初始位置进行搜索,每进行一次就更新一次最少步数。
BFS就是从八个方向搜索,一搜索到指定的位置就返回步数
BFS的代码:
#include<stdio.h> #include<string.h> int dx[] = {-1, -1, -2, -2, 1, 1, 2, 2}; int dy[] = {-2, 2, -1, 1, -2, 2, -1, 1}; int x1, y1, x2, y2; int num; typedef struct knight{ int x, y, d; }; void bfs(int x, int y){ int vis[100][100]; knight q[100]; int front = 0, near = 1; memset(vis, 0, sizeof(vis)); memset(q, 0, sizeof(q)); q[0].x = x; q[0].y = y; q[0].d = 0; vis[x][y] = 1; while(front < near){ for(int i = 0; i < 8; i++){ int tx = q[front].x + dx[i]; int ty = q[front].y + dy[i]; if(tx >= 0 && tx < 8 && ty >= 0 && ty < 8 && !vis[tx][ty]){ if(tx == x2 && ty == y2) { num = q[front].d + 1; return; } vis[tx][ty] = 1; q[near].x = tx; q[near].y = ty; q[near].d = q[front].d + 1; near++; } } front++; } } int main(){ char c1, c2, c3, c4; while(scanf("%c%c %c%c", &c1, &c2, &c3, &c4) != EOF){ getchar(); x1 = c1 - 'a'; y1 = c2 - '1'; x2 = c3 - 'a'; y2 = c4 - '1'; num = 0; if(x1 != x2 || y1 != y2) bfs(x1, y1); printf("To get from %c%c to %c%c takes %d knight moves.\n", c1, c2, c3, c4, num); } return 0; }
DFS的代码:
#include<stdio.h> #include<string.h> int map[10][10]; int dx[] = {-1, -1, -2, -2, 1, 1, 2, 2}; int dy[] = {-2, 2, -1, 1, -2, 2, -1, 1}; void dfs(int x, int y, int t){ if(x > 7 || x < 0 || y > 7 || y < 0 || map[x][y] <= t) return; map[x][y] = t; for(int i = 0; i < 8; i++) { int tx = x + dx[i]; int ty = y + dy[i]; dfs(tx, ty, t + 1); } } int main(){ char c1, c2, c3, c4; while(scanf("%c%c %c%c", &c1, &c2, &c3, &c4) != EOF){ getchar(); int x1, x2, y1, y2; x1 = c1 - 'a'; y1 = c2 - '1'; x2 = c3 - 'a'; y2 = c4 - '1'; for(int i = 0; i < 8; i++) for(int j = 0; j < 8; j++) map[i][j] = 20; dfs(x1, y1, 0); printf("To get from %c%c to %c%c takes %d knight moves.\n", c1, c2, c3, c4, map[x2][y2]); } return 0; }