uva 439 - Knight Moves
来源:互联网 发布:网络招嫖2016最大案件 编辑:程序博客网 时间:2024/05/20 10:54
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;int vis[10][10], ans[100];;int step[10][3]= {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{-2,1},{2,-1},{-2,-1}};int bfs(int x1, int y1, int x2, int y2){ int front = 0, rear = 1, list[100][3]; list[front][0] = x1; list[front][1] = y1; vis[x1][y1] = 1; ans[front] = 0; while(front < rear) { for(int i = 0; i < 8; i++) { int x = step[i][0] + list[front][0], y = step[i][1] + list[front][1]; if(x>0 && x<=8 && y>0 && y<=8 && !vis[x][y]) { if(x == x2 && y == y2) return ans[front]+1; list[rear][0] = x; list[rear][1] = y; ans[rear++] = ans[front] + 1; vis[x][y] = 1; } } front++; } return 0;}int main(){ char s1[3], s2[3]; while(cin >> s1 >> s2) { memset(vis, 0, sizeof(vis)); memset(ans, 0, sizeof(ans)); int count = bfs(s1[1]-'0', s1[0]-'a'+1, s2[1]-'0', s2[0]-'a'+1); printf("To get from %s to %s takes %d knight moves.\n", s1, s2, count ); } return 0;}