Knight Moves
题意:骑士巡游到某位置的最少步数
#include <stdio.h> #include <string.h> int s[20][20]; int rear, front; int min; char a, c; int b, d; struct { int x, y; int p; }Susake[300000]; void bfs(int n, int m) { int t; rear++; Susake[rear].x = n; Susake[rear].y = m; Susake[rear].p = 0; if(n == c - 96 && m == d) { min = Susake[rear].p; return ; } while(front != rear) { front++; t = front; if(s[Susake[t].x - 2][Susake[t].y + 1]) { rear++; Susake[rear].x = Susake[t].x - 2; Susake[rear].y = Susake[t].y + 1; Susake[rear].p = Susake[t].p + 1; if(Susake[rear].x == c - 96 && Susake[rear].y == d) { min = Susake[rear].p; return ; } } if(s[Susake[t].x + 2][Susake[t].y + 1]) { rear++; Susake[rear].x = Susake[t].x + 2; Susake[rear].y = Susake[t].y + 1; Susake[rear].p = Susake[t].p + 1; if(Susake[rear].x == c - 96 && Susake[rear].y == d) { min = Susake[rear].p; return ; } } if(s[Susake[t].x - 1][Susake[t].y + 2]) { rear++; Susake[rear].x = Susake[t].x - 1; Susake[rear].y = Susake[t].y + 2; Susake[rear].p = Susake[t].p + 1; if(Susake[rear].x == c - 96 && Susake[rear].y == d) { min = Susake[rear].p; return ; } } if(s[Susake[t].x - 2][Susake[t].y - 1]) { rear++; Susake[rear].x = Susake[t].x - 2; Susake[rear].y = Susake[t].y - 1; Susake[rear].p = Susake[t].p + 1; if(Susake[rear].x == c - 96 && Susake[rear].y == d) { min = Susake[rear].p; return ; } } if(s[Susake[t].x - 1][Susake[t].y - 2]) { rear++; Susake[rear].x = Susake[t].x - 1; Susake[rear].y = Susake[t].y - 2; Susake[rear].p = Susake[t].p + 1; if(Susake[rear].x == c - 96 && Susake[rear].y == d) { min = Susake[rear].p; return ; } } if(s[Susake[t].x + 1][Susake[t].y - 2]) { rear++; Susake[rear].x = Susake[t].x + 1; Susake[rear].y = Susake[t].y - 2; Susake[rear].p = Susake[t].p + 1; if(Susake[rear].x == c - 96 && Susake[rear].y == d) { min = Susake[rear].p; return ; } } if(s[Susake[t].x + 2][Susake[t].y - 1]) { rear++; Susake[rear].x = Susake[t].x + 2; Susake[rear].y = Susake[t].y - 1; Susake[rear].p = Susake[t].p + 1; if(Susake[rear].x == c - 96 && Susake[rear].y == d) { min = Susake[rear].p; return ; } } if(s[Susake[t].x + 1][Susake[t].y + 2]) { rear++; Susake[rear].x = Susake[t].x + 1; Susake[rear].y = Susake[t].y + 2; Susake[rear].p = Susake[t].p + 1; if(Susake[rear].x == c - 96 && Susake[rear].y == d) { min = Susake[rear].p; return ; } } } } int main(int argc, char *argv[]) { int i, j; while(scanf("%c%d%*c%c%d%*c", &a, &b, &c, &d) != EOF) { memset(s, 0, sizeof(s)); front = rear = 0; for(i = 1; i <= 8; i++) for(j = 1; j <= 8; j++) s[i][j] = 1; bfs(a - 96, b); printf("To get from %c%d to %c%d takes %d knight moves.\n", a, b, c, d, min); } return 0; }
时间: 2024-10-25 08:08:54