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);
}
}
#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);
}
}
相关文章推荐
- DIV始终固定在网页右下角位置的CSS实现方法,返回顶部功能
- acm题目及我的程序(2)——Knight Moves (骑士跳跃) ——任意两点间的最短路径所有信息(算法2)
- jquery插件:任意位置浮动固定层
- CodeForces 599A Patrick and Shopping (商店购物最短路程)
- 滚动条固定位置
- 固定导航栏的位置
- 如何让DIV固定在页面的某个位置而不随着滚动条随意滚动
- 多个相机固定空间位置的简单拼接orb_flann
- JQUERY实现网页右下角固定位置展开关闭特效的方法
- Fixed固定位置的悬浮div层
- Study Html《如何让DIV固定在页面的某个位置而不随着滚动条随意滚动》
- EasyUI datagrid : 启用行号、固定列及多级表头后,头部行号位置单元格错位的问题
- android百度地图开发之自动定位所在位置与固定位置进行驾车,步行,公交路线搜索
- 网页滚动时固定顶部菜单的位置 - 两种方案比较
- poj 1456 Supermarket (最短路程)
- css网页背景固定位置不变
- 随机位置+固定位置排序
- javascript实现的固定位置悬浮窗口实例
- 弹出div或者弹出新窗口的固定位置、固定大小
- GDI+在固定位置(固定点)的地方绘制文本