UVA 439 - Knight Moves

来源:互联网 发布:游戏耳机推荐 知乎 编辑:程序博客网 时间:2024/06/06 00:29

简单题,图的BFS遍历

#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <string>#include <queue>#include <utility>using namespace std;const int size = 8;int a[size][size];int d[][2] = { {2 , 1} , {-2 , 1} , {2 , -1} , {-2 , -1} ,               {1 , 2} , {-1 , 2} , {1 , -2} , {-1 , -2}};int main(){char buffer1[8] , buffer2[8];while(scanf("%s%s" , buffer1 , buffer2) == 2){int src[2] , des[2];src[0] = buffer1[0] - 'a';src[1] = buffer1[1] - '1';des[0] = buffer2[0] - 'a';des[1] = buffer2[1] - '1';int x , y;memset(a , -1 , sizeof(a));a[src[0]][src[1]] = 0;queue< pair<int , int> > q;q.push(make_pair(src[0] , src[1]));while( !q.empty() ){x = q.front().first;y = q.front().second;q.pop();if( x == des[0] && y == des[1]) break;for(int i = 0 ; i < 8 ; ++i){int tx = x + d[i][0];int ty = y + d[i][1];if(tx < 0 || tx >= size) continue;if(ty < 0 || ty >= size) continue;if(a[tx][ty]>=0) continue;a[tx][ty] = a[x][y] + 1;q.push(make_pair(tx , ty));}}printf("To get from %s to %s takes %d knight moves.\n" , buffer1 , buffer2 , a[x][y]);}return 0;}


0 0