您的位置:首页 > 其它

439骑士走到固定位置最短路程

2011-07-27 12:07 204 查看
#include <iostream>

#include <cstring>

#include <cstdio>

#define MAX 10

using namespace std;

int q[MAX*MAX]; //·½¸ñ

int dist[MAX][MAX]; // ¾àÀë

int vis[MAX][MAX];

int dx[] = {-1,-2,-2,-1,1,2,2,1};

int dy[] = {-2,-1,1,2,2,1,-1,-2};

int bfs(int x,int y,int a,int b)

{

if(x == a && y == b) return 0;

memset(vis,0,sizeof(vis));

int front = 0,rear = 0,u;

u = x * 8 + y;

dist[x][y] = 0;

q[rear++] = u;

while(front < rear)

{

u = q[front++];

x = u / 8; y = u % 8;

if( y == 0) {y = 8;x = x-1;};

for(int i = 0;i < 8;i++)

{

int nx = x+dx[i],ny = y+dy[i];

if(nx >0 && nx <= 8 && ny > 0 && ny <=8 && !vis[nx][ny])

{

int v = nx*8 + ny;

q[rear++] = v;

vis[nx][ny] = 1;

dist[nx][ny] = dist[x][y] + 1;

if(nx == a && ny == b) return dist[a][b];

}

}

}

}

int main()

{

// freopen("in.in","r",stdin);

char x[3],y[3];

while(scanf("%s%s",x,y) == 2)

{

int count;

if(x[0] < y[0] || (x[0] == y[0] && x[1] <= y[1])){

count = bfs(y[1]-'0',y[0]-'a'+1,x[1]-'0',x[0]-'a'+1);

}

else{

count = bfs(x[1]-'0',x[0]-'a'+1,y[1]-'0',y[0]-'a'+1);

}

printf("To get from %s to %s takes %d knight moves.\n",x,y,count);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: