首页 > 代码库 > UVa439
UVa439
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;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。